Python初始化列表列表 [英] Python initializing a list of lists
问题描述
可能重复:
Python列表附加行为
Possible Duplicate:
Python list append behavior
我打算初始化一个长度为n的列表列表.
I intend to initialize a list of list with length of n.
x = [[]] * n
但是,这以某种方式将列表链接在一起.
However, this somehow links the lists together.
>>> x = [[]] * 3
>>> x[1].append(0)
>>> x
[[0], [0], [0]]
我希望有类似的东西:
[[], [0], []]
有什么想法吗?
推荐答案
问题是它们在内存中的列表完全相同.使用[x]*n
语法时,得到的是n
许多x
对象的列表,但是它们都是对同一对象的引用.它们不是不同的实例,而只是对同一实例的n
引用.
The problem is that they're all the same exact list in memory. When you use the [x]*n
syntax, what you get is a list of n
many x
objects, but they're all references to the same object. They're not distinct instances, rather, just n
references to the same instance.
要列出3个不同的列表,请执行以下操作:
To make a list of 3 different lists, do this:
x = [[] for i in range(3)]
这为您提供了[]
的3个单独实例,这就是您想要的
This gives you 3 separate instances of []
, which is what you want
[[]]*n
类似于
l = []
x = []
for i in range(n):
x.append(l)
[[] for i in range(3)]
类似于:
x = []
for i in range(n):
x.append([]) # appending a new list!
In [20]: x = [[]] * 4
In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object
In [22]: x=[[] for i in range(4)]
In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time
这篇关于Python初始化列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!