Python复制列表列表 [英] Python copy a list of lists

查看:101
本文介绍了Python复制列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using python 3.4.1.
For a single list a=[1,2], if I make a copy of it, b = a.copy() when I change items in b, it won't change items in a.
However, when I define a list of lists (actually a matrix) a = [[1,2],[3,4]], when I assign b = a.copy(). What I do to list b actually affects a.
I checked their addresses, they are different.
Can anyone tell me why?

ps:我所做的是b[0][0] = x,并且a中的项目也已更改.

ps: What I did is b[0][0] = x, and the item in a was also changed.

推荐答案

copy 模块:

浅层复制和深层复制之间的区别仅与复合对象(包含其他对象的对象,如列表或类实例)有关:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • 浅表副本会构造一个新的复合对象,然后(在可能的范围内)将对原始对象中引用的对象的引用插入其中.
  • 深层副本会构造一个新的复合对象,然后递归地将原始对象中的对象的副本插入其中.

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

When you call regular copy.copy() you are performing a shallow copy. This means that in a case of a list-of-lists, you will get a new copy of the outer list, but it will contain the original inner lists as its elements. Instead you should use copy.deepcopy(), which will create a new copy of both the outer and inner lists.

在使用copy([1,2])的第一个示例中没有注意到这一点的原因是,像int这样的基元是不可变的,因此,如果不创建新实例就无法更改其值.如果列表的内容改为是可变对象(如列表或具有可变成员的任何用户定义对象),则在列表的两个副本中都将看到这些对象的任何变异.

The reason that you didn't notice this with your first example of using copy([1,2]) is that the primitives like int are immutable, and thus it is impossible to change their value without creating a new instance. If the contents of the list had instead been mutable objects (like lists, or any user-defined object with mutable members), any mutation of those objects would have been seen in both copies of the list.

这篇关于Python复制列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆