Python初始化列表列表 [英] Python initializing a list of lists

查看:92
本文介绍了Python初始化列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
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屋!

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