对于 args= ['', '0', 'P1', 'with', '10']
和 students=[['1', '2', ' 3', 6]]
它打印:
[[['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)
最佳答案
[:]
进行浅拷贝。您需要一个深拷贝:
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解释浅复制和深复制之间的区别:
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
关于Python list.append 之后更改元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46988924/