Python列表列表初始化 [英] Python list of list initialize
问题描述
我知道
[[]] * 10
将给出10个相同的空引用,并且
will give 10 references of the same empty, And
[[] for i in range(10)]
将给出10个空列表.但在此示例中:
will give 10 empty lists. But in this example:
def get_list(thing):
return [thing for i in range(10)]
a = get_list([])
a[0].append(1)
print(a)
为什么再次显示结果
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
与问题不同列表更改列表意外反映在子列表之间,我知道Python不会在[x]*10
中进行复制.
Unlike question List of lists changes reflected across sublists unexpectedly , I understand that Python doesn't do copy in [x]*10
.
但是为什么[]
在[[] for i in range(10)]
中是特殊的呢?我认为这是不一致的.
But why []
is special in [[] for i in range(10)]
? I think this is inconsistent. Instead of creating a empty list []
then pass to [ ___ for i in range(10)]
, Python take "[]" literally and execute "[]" for every i
.
推荐答案
这是因为thing
是相同的列表.
That is because thing
is the same list.
在[[] for i in range(10)]
中,每次都会生成一个新列表.
In [[] for i in range(10)]
a new list is generated every time.
在[thing for i in range(10)]
中,它始终是名为thing
的列表.
In [thing for i in range(10)]
it's always the list named thing
.
这篇关于Python列表列表初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!