2017-10-28 71 views
1

对于args= ['', '0', 'P1', 'with', '10']students=[['1', '2', '3', 6]]它打印:Python的list.append变化的元素之后

[[['1', '2', '3', 6]]] 
[[['10', '2', '3', 6]]] 

预期产量为:

[[['1', '2', '3', 6]]] 
[[['1', '2', '3', 6]]] 

但它在某种程度上改变了backup_list任何快速解决方案?

backup_list.append(students[:]) 
print(backup_list) 
students[int(args[1])][0] = args[4] 
print(backup_list) 

回答

1

[:]做出浅拷贝。你需要一个深层副本:

import copy 

backup_list.append(copy.deepcopy(students)) 

全部程序:

import copy 

backup_list = [] 
args= ['', '0', 'P1', 'with', '10'] 
students=[['1', '2', '3', 6]] 
backup_list.append(copy.deepcopy(students)) 
print(backup_list) 
students[int(args[1])][0] = args[4]  
print(backup_list) 

输出:

[[['1', '2', '3', 6]]] 
[[['1', '2', '3', 6]]] 

documentation解释浅和深拷贝之间的区别:

一浅拷贝构造一个新的复合对象然后 (尽可能)将引用插入到原来的 中找到的对象中。

深拷贝构造一个新的复合对象,然后递归地将 拷贝插入原始对象中。

+0

非常感谢它,但是您能否更深入地解释它为什么会这样做以及它为什么不具有浅拷贝:3? – Skillwalker

相关问题