了解清单清单 [英] Understanding lists of lists
问题描述
可能重复:
Python列表列表中的意外功能
Python列表混乱
Possible Duplicate:
Unexpected feature in a Python list of lists
Python list confusion
考虑以下代码:
a = [[]] * 3
a[1].append("foo")
我希望a
的值变为:
[[], ["foo"], []]
相反,a
的每个元素都会更新:
instead, every element of a
is updated:
[["foo"], ["foo"], ["foo"]]
有人可以解释为什么列表中的每个元素而不是仅定义的元素(a[1]
)被更新了吗?我的逻辑有根本上的错误吗?
Can someone please explain why did each element of the list got updated instead of just the defined element (a[1]
)? Is there something fundamentally wrong in my logic?
对于运行我的Python2.7的价值而言
For what it's worth I'm running Python2.7
推荐答案
Python中的列表是对象,这意味着当您将列表分配给另一个变量时,更改其中任何一个都会更改实际列表,例如
Lists in Python are objects, this means when you assign a list to another variable, changing either will change the actual list, for example
a = []
b = a
b.append("hi")
print a
// a is now ["hi"]
完成任务时
a = [[]] * 3
这跟说的一样
inner_list = []
outer_list = [inner_list, inner_list, inner_list]
换句话说,所有内部列表都是 same 对象.正如您所想,没有不同的对象.
In other words, all the inner lists are the same object. Not different objects as you think.
要获得想要的效果,您应该这样做:
To get the effect you want, you should do:
outer_list = []
for i in range(0, 3):
outer_list.append([])
哪个会创建3个内部列表对象,然后将其放入外部对象.
Which creates a 3 inner lists objects and puts the into the outer object.
这篇关于了解清单清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!