Python复制列表列表

Python copy a list of lists

本问题已经有最佳答案,请猛点这里访问。

我使用的是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中的项目也改变了。


从文档的copy模块:

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.

当你呼叫你的正则copy.copy()表演a浅拷贝。这意味着,在A Case of a list(列表,你会得到一个新的外部复制战略,但它不包含作为其内部原有的列表元素。相反,你应该使用copy.deepcopy(),这将创建一个新的外部和内部两个副本列表。

原因你不通告你这个例子使用的是第一copy([1,2])推样int是不可变的,因此它是不可能改变他们的价值没有创建一个新实例。如果内容是一个列表对象(而不是mutable样列表,或任何用户定义的对象和成员的任何突变mutable),这些对象是已经在这两个湖泊的副本列表。


也许理解搜索列表为:

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

如果你是...though快比一层矩阵的列表是不理解,不只是使用deepcopy优雅。

一个编辑区,浅拷贝,想安静的对象引用包含在列表中。这样的做法……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> 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


它是非常简单的,只是做的是:

1
b = a

例如:

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