追加到Python中的嵌套列表 [英] appending to a nested list in python
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument\">Least惊讶,在Python:该可变默认参数结果
<一href=\"http://stackoverflow.com/questions/1605024/python-using-the-multiply-operator-to-create-copies-of-objects-in-lists\">Python - 使用乘法运算符来
当我追加到一个列表,这是另一个列表Python的表现出乎意料。这里有一个例子:
Python behaves unexpected when i append to a list, which is in another list. Here's an example:
>>> _list = [[]] * 7
>>> _list
[[], [], [], [], [], [], []]
>>> _list[0].append("value")
我所期望的:
>>> _list
[['value'], [], [], [], [], [], []]
我得到什么:
>>> _list
[['value'], ['value'], ['value'], ['value'], ['value'], ['value'], ['value']]
这是为什么?我怎么能去解决它?
Why is this? how can i go around it?
推荐答案
您的问题是,你的清单中不包含七个独立列出,而是的相同列表中七次。
Your problem is that your list does not contain seven independent lists, but rather the same list seven times.
要创建的目录列表,更好地利用列表COM prehension:
To create a list of list, better use a list comprehension:
_list = [[] for _ in xrange(7)]
,这将导致含有七个不同的列表的列表。
which will result in a list containing seven different lists.
这篇关于追加到Python中的嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!