How to make a copy of a list of objects not change when modifying the original list?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicates:
How to clone a list in python?
What is the best way to copy a list in Python?
1 2 3 | original_list = [Object1(), Object2(), Object3()] copy_list = original_list original_list.pop() |
如果我从原始列表中删除了一个对象,那么如何防止副本列表发生更改呢?
原始清单
1 | [<Object.Object instance at 0x00EA29E0>, <Object.Object instance at 0x00EA2DC8>, <Object.Object instance at 0x00EA2EE0>] |
弹出原始列表后复制列表(我希望此值等于上面的值)
1 | [<Object.Object instance at 0x00EA29E0>, <Object.Object instance at 0x00EA2DC8>] |
使用copy.deep copy()进行深度复制:
1 2 | import copy copy_list = copy.deepcopy(original_list) |
对于浅拷贝,使用copy.copy():
1 2 | import copy copy_list = copy.copy(original_list) |
或切片,但未指定终结点:
1 | copy_list = original_list[:] |
有关深度和浅层副本的说明,请参阅副本文档。
这行得通。
1 2 | import copy copy_list = copy.copy(original_list) |
阿尔索
1 | copy_list = list(original_list) |
使用深拷贝
Return a deep copy of x.
1 2 3 4 5 | from copy import deepcopy original_list = [Object1(), Object2(), Object3()] copy_list = deepcopy(original_list) original_list.pop() |
但请注意,在您的情况下,切片将更快地工作:
1 | copy_list = original_list[:] |