Python:如何在列表列表中追加新元素? [英] Python : how to append new elements in a list of list?

查看:98
本文介绍了Python:如何在列表列表中追加新元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的程序:

Here is a very simple program:

 a = [[]]*3

 print str(a)

 a[0].append(1)
 a[1].append(2)
 a[2].append(3)

 print str(a[0])
 print str(a[1])
 print str(a[2])

这是我期望的输出:

 [[], [], []]
 [1]
 [2]
 [3]

但是我得到了这个:

 [[], [], []]
 [1, 2, 3]
 [1, 2, 3]
 [1, 2, 3]

确实有些东西我不能到达这里!

There is really something I do not get here !

推荐答案

您必须这样做

a = [[] for i in xrange(3)]

不是

a = [[]]*3

现在可以使用了:

$ cat /tmp/3.py
a = [[] for i in xrange(3)]

print str(a)

a[0].append(1)
a[1].append(2)
a[2].append(3)

print str(a[0])
print str(a[1])
print str(a[2])

$ python /tmp/3.py
[[], [], []]
[1]
[2]
[3]

当您执行类似a = [[]]*3的操作时,您会在列表中获得3次相同的列表[]. 相同意味着当您更改其中一个时,您也会更改所有它们(因为只有一个列表被引用了3次).

When you do something like a = [[]]*3 you get the same list [] three times in a list. The same means that when you change one of them you change all of them (because there is only one list that is referenced three times).

您需要创建三个独立的列表来规避此问题.您可以通过列表理解来做到这一点.您在此处构造一个列表,该列表由独立的空列表[]组成.将为xrange(3)上的每次迭代创建一个新的空列表(在这种情况下,rangexrange之间的区别并不那么重要;但是xrange会好一点,因为它不会产生以下内容的完整列表)数字并返回一个迭代器对象).

You need to create three independent lists to circumvent this problem. And you do that with a list comprehension. You construct here a list that consists of independent empty lists []. New empty list will be created for each iteration over xrange(3) (the difference between range and xrange is not so important in this case; but xrange is a little bit better because it does not produce the full list of numbers and just returns an iterator object instead).

这篇关于Python:如何在列表列表中追加新元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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