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

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

问题描述

我创建了一个列表列表并希望将项目附加到各个列表,但是当我尝试附加到其中一个列表 (a[0].append(2)) 时,项目被添加到所有列表中.

a = []b = [1]a.附加(b)a.附加(b)a[0].append(2)a[1].append(3)打印(一)

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

而我期望的是:[[1, 2], [1, 3]]

改变我构造初始列表列表的方式,使 b 成为一个浮点数而不是一个列表,并将括号放在 .append() 中,给了我想要的输出:

a = []乙 = 1a.append([b])a.append([b])a[0].append(2)a[1].append(3)打印(一)

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

但是为什么呢?结果应该不同是不直观的.我知道这与 多次引用相同列表,但我不知道发生了什么.

解决方案

这是因为列表包含对对象的引用.您的列表不包含 [[1 2 3] [1 2 3]],它是 [<对 b 的引用>].

当您更改对象时(通过将某些内容附加到 b),您正在更改对象本身,而不是包含该对象的列表.

要获得您想要的效果,您的列表a 必须包含b 的副本,而不是对b 的引用.要复制列表,您可以使用范围 [:].例如:

<预><代码>>>>a=[]>>>b=[1]>>>a.append(b[:])>>>a.append(b[:])>>>a[0].append(2)>>>a[1].append(3)>>>打印一个[[1, 2], [1, 3]]

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)

Gives: [[1, 2, 3], [1, 2, 3]]

Whereas I would expect: [[1, 2], [1, 3]]

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)

Gives: [[1, 2], [1, 3]]

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.

解决方案

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

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

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(bar) 会影响列表列表中的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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