>>> this = [1, 2]
>>> that = [33, 44]
>>> stuff = [this, that]
>>> other = stuff[:]
>>> other
[[1, 2], [33, 44]]
>>> other[0][0] = False
>>> stuff
[[False, 2], [33, 44]] #the same problem as before
>>> this
[False, 2] #original list also changed
>>> other = [x[:] for x in stuff]
>>> other
[[False, 2], [33, 44]]
>>> other[0][0] = True
>>> other
[[True, 2], [33, 44]]
>>> stuff
[[False, 2], [33, 44]] #copied matrix is different
>>> this
[False, 2] #original was unchanged by this assignment
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
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.
也许是这样的清单理解:
……尽管如果矩阵的深度超过一个层,列表理解可能不如仅仅使用
deepcopy
那么优雅。编辑-如前所述,浅层副本仍将包含对列表中对象的引用。例如。。。
很简单,就这么做:
示例:
从^{} 模块的文档中:
当您调用regular
copy.copy()
时,您正在执行一个浅拷贝。这意味着在列表列表的情况下,您将获得外部列表的新副本,但它将包含原始的内部列表作为其元素。相反,您应该使用copy.deepcopy()
,这将创建外部和内部列表的新副本。在第一个使用
copy([1,2])
的示例中没有注意到这一点的原因是int
这样的原语是不可变的,因此不创建新实例就不可能更改它们的值。如果列表的内容是可变对象(如列表,或任何具有可变成员的用户定义对象),则在列表的两个副本中都会看到这些对象的任何变化。相关问题 更多 >
编程相关推荐