Python 初始化列表列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12791501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:53:08  来源:igfitidea点击:

Python initializing a list of lists

pythonlist

提问by Amir

Possible Duplicate:
Python list append behavior

可能重复:
Python 列表追加行为

I intend to initialize a list of list with length of n.

我打算初始化一个长度为 n 的列表列表。

x = [[]] * n

However, this somehow links the lists together.

但是,这以某种方式将列表链接在一起。

>>> x = [[]] * 3
>>> x[1].append(0)
>>> x
[[0], [0], [0]]

I expect to have something like:

我希望有类似的东西:

[[], [0], []]

Any ideas?

有任何想法吗?

采纳答案by inspectorG4dget

The problem is that they're all the same exact list in memory. When you use the [x]*nsyntax, what you get is a list of nmany xobjects, but they're all references to the same object. They're not distinct instances, rather, just nreferences to the same instance.

问题是它们在内存中都是完全相同的列表。当您使用该[x]*n语法时,您得到的是n许多x对象的列表,但它们都是对同一对象的引用。它们不是不同的实例,而是n对同一个实例的引用。

To make a list of 3 different lists, do this:

要制作 3 个不同列表的列表,请执行以下操作:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

这为您提供了 3 个单独的 实例[],这正是您想要的

[[]]*nis similar to

[[]]*n类似于

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)]is similar to:

虽然[[] 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