首页 > 编程语言 > 详细

【python拾遗】list对象处理失败

时间:2020-12-18 19:10:40      阅读:29      评论:0      收藏:0      [点我收藏+]

【python拾遗】list对象处理失败

情形:今天在处理文件的时候发现

list_a = [a, b, c, d]
for i in range(2):
    temp = list_a
	temp[2] = temp[2] + "_i"
    print(temp[2])

想象输出是:

想象输出	| 实际输出
c_0	|	c_0
c_1	|	c_0_1
c_2	|	c_0_1_2

隐隐感觉那里不对。怎么temp起不到作用了呢?

有以下几个问题

  1. temp=list_a 真实作用是什么?
  2. list复制的操作怎么完成?

心里隐隐有了一点答案,python入门时记得变量相当于C指针,指向不同的对象

回过头查找python变量的描述得知:

Python变量是一个符号名称,它是对对象的引用或指针。将对象分配给变量后,即可使用该名称引用该对象。但是数据本身仍然包含在对象中。

现在回答问题0:

Q: temp=list_a 真实作用是什么?

R: 使temp和list_a一样指向了同一个list对象。

通过检索得到了list对象的几个复制(拷贝)方法

  • 浅拷贝:需导入标准库 import copy

    使用copy.copy()复制了对象,对象中的元素未复制。

  • 深拷贝:需导入标准库 import copy

    使用copy.deepcopy()复制了对象以及对象中的元素。

  • 特殊拷贝:

    list_a[:], list(list_a), list_a*1, copy.copy(a).

    结果等同,都是浅拷贝

import copy
list_a = [1,2,3,[4,5,6],7,8]
temp = list_a
temp1 = list_a[:]
temp2 = copy.copy(list_a)        
temp3 = copy.deepcopy(list_a)
temp4 = list(list_a)
temp5 = list_a*1
list_a[2] = 12
list_a[3].append(14)
print(list_a, temp, temp1, temp2, temp3, temp4, temp5, sep=‘\n‘)

[1, 2, 12, [4, 5, 6, 14], 7, 8] #赋值
[1, 2, 12, [4, 5, 6, 14], 7, 8]	#list_a
[1, 2, 3, [4, 5, 6, 14], 7, 8]	#list_a[:]
[1, 2, 3, [4, 5, 6, 14], 7, 8]	#copy.copy(list_a) 
[1, 2, 3, [4, 5, 6], 7, 8]	#copy.deepcopy(list_a)
[1, 2, 3, [4, 5, 6, 14], 7, 8]	#list(list_a)
[1, 2, 3, [4, 5, 6, 14], 7, 8]	#list_a*1

【python拾遗】list对象处理失败

原文:https://www.cnblogs.com/cpdragon/p/14156110.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!