[英]Elements of list change despite cloning in Python
In the following Python code, I created a list a which contains a number of lists, and then created a copy of it, b, but unlike with lists that do not contain other lists, when b is changed, a also changes accordingly.在下面的 Python 代码中,我创建了一个包含多个列表的列表 a,然后创建了它的副本 b,但与不包含其他列表的列表不同,当 b 更改时,a 也会相应更改。 Can someone explain how to prevent this from happening other than by copying each list separately?
除了单独复制每个列表之外,有人可以解释如何防止这种情况发生吗?
a = [[None, None, None], [None, None, None], [None, None, None]]
b=a[:]
b[0][0] = 5
a
[[5, None, None], [None, None, None], [None, None, None]]
b
is a shallow copy of a
(check out the values id(a[0])
and id(b[0])
, they will be same even if id(a)
!= id(b)
). b
是a
的浅拷贝(查看id(a[0])
和id(b[0])
的值,即使id(a)
!= id(b)
也是相同的)。 You need to take care of the elements inside the list as well (if they are mutable and modified, a shallow copy will reflect the changes in both the places).您还需要注意列表中的元素(如果它们是可变的和修改的,浅拷贝将反映这两个地方的更改)。 You can do something like this to create a
deep
copy:您可以执行以下操作来创建
deep
副本:
import copy
b = copy.deepcopy(a)
Read up on shallow and deep copy operations in Python.阅读 Python 中的浅拷贝和深拷贝操作。
The slice creates a new list, but the contents of the list are not copied.切片会创建一个新列表,但不会复制列表的内容。 So,
a[:]
gets you a new list, but the contents of that new list b
are still references to the same lists that are referenced from a
.因此,
a[:]
为您提供了一个新列表,但该新列表b
的内容仍然是对从a
引用的相同列表的引用。
If you would try b[0]=[]
, you'd be able to tell you can modify b
without changing a
, but b[0][0]
just modifies the first element of the first list in b
, which is the first element of the first list in a
as well.如果您尝试
b[0]=[]
,您可以告诉您可以在不更改a
情况下修改b
,但是b[0][0]
只是修改b
中第一个列表的第一个元素,即a 中第一个列表的第a
元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.