为什么foo.append(巴)影响列表的列表的所有元素? [英] Why does foo.append(bar) affect all elements in a list of lists?

查看:93
本文介绍了为什么foo.append(巴)影响列表的列表的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建列表的列表,并要追加项目到个人名单,但是当我尝试添加到列表中的一个( A [0] .append(2)),该项目被添加到所有列表。

I create a list of lists and want to append items to the individual lists, but when I try to append to one of the lists (a[0].append(2)), the item gets added to all lists.

a=[]
b=[1]

a.append(b)
a.append(b)

a[0].append(2)
a[1].append(3)
print a

给出: [[1,2,3],[1,2,3]

而我希望: [1,2],[1,3]]

更改我构造列表的初始列表的方式,使 B A浮动,而不是一个列表,并把里面的.append()括号,给我所需的输出

Changing the way I construct the initial list of lists, making b a float instead of a list and putting the brackets inside .append(), gives me the desired output:

a=[]
b=1

a.append([b])
a.append([b])

a[0].append(2)
a[1].append(3)
print a

给出: [1,2],[1,3]]

但是,为什么?它是不直观的结果应该是不同的。我知道这与那里是<一个做href=\"http://stackoverflow.com/questions/5280799/list-append-changing-all-elements-to-the-appended-item\">multiple相同的列表引用,但我没有看到正在发生。

But why? It is not intuitive that the result should be different. I know this has to do with there being multiple references to the same list, but I don't see where that is happening.

推荐答案

这是因为列表包含对对象的引用。您的列表中不包含 [1 2 3] [1 2 3]] ,这是 [&lt;参考,以B&GT; &lt;参考,以B&GT;。]

It is because the list contains references to objects. Your list doesn't contain [[1 2 3] [1 2 3]], it is [<reference to b> <reference to b>].

当你改变对象(通过附加的东西 B ),您将更改包含对象的对象本身,而不是名单。

When you change the object (by appending something to b), you are changing the object itself, not the list that contains the object.

要得到你想要的效果,你的清单 A 必须包含的拷贝b ,而不是引用 b 。要复制一个列表,您可以使用范围 [:] 。例如,

To get the effect you desire, your list a must contain copies of b rather than references to b. To copy a list you can use the range [:]. For example, :

>>> a=[]
>>> b=[1]
>>> a.append(b[:])
>>> a.append(b[:])
>>> a[0].append(2)
>>> a[1].append(3)
>>> print a
[[1, 2], [1, 3]]

这篇关于为什么foo.append(巴)影响列表的列表的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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