Python复制列表列表

2024-03-29 06:23:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python 3.4.1。
对于单个列表a=[1,2],如果我复制它,b = a.copy()当我在b中更改项时,它不会在a中更改项。
但是,当我定义一个列表列表(实际上是一个矩阵)a = [[1,2],[3,4]]时,当我分配b = a.copy()时。我所做的列出b实际上会影响a
我查了他们的地址,他们不一样。
有人能告诉我为什么吗?

注:我做的是b[0][0] = x,a中的项也被更改了。


Tags: 列表定义地址矩阵copy项时
3条回答

也许是这样的清单理解:

new_list = [x[:] for x in old_list]

……尽管如果矩阵的深度超过一个层,列表理解可能不如仅仅使用deepcopy那么优雅。

编辑-如前所述,浅层副本仍将包含对列表中对象的引用。例如。。。

>>> 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

很简单,就这么做:

b = a

示例:

>>> a = [1, 2, 3]
>>> b = a
>>> b.append(4)
>>> b
[1, 2, 3, 4]
>>> a
[1, 2, 3, 4]

^{}模块的文档中:

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.

当您调用regularcopy.copy()时,您正在执行一个浅拷贝。这意味着在列表列表的情况下,您将获得外部列表的新副本,但它将包含原始的内部列表作为其元素。相反,您应该使用copy.deepcopy(),这将创建外部和内部列表的新副本。

在第一个使用copy([1,2])的示例中没有注意到这一点的原因是int这样的原语是不可变的,因此不创建新实例就不可能更改它们的值。如果列表的内容是可变对象(如列表,或任何具有可变成员的用户定义对象),则在列表的两个副本中都会看到这些对象的任何变化。

相关问题 更多 >