附加到python中的嵌套列表

时间:2012-12-07 12:30:35

标签: python list nested append

  

可能重复:
  “Least Astonishment” in Python: The Mutable Default Argument
  Python - Using the Multiply Operator to Create Copies of Objects in Lists

当我附加到另一个列表中的列表时,Python会出现意外行为。这是一个例子:

>>> _list = [[]] * 7
>>> _list
[[], [], [], [], [], [], []]
>>> _list[0].append("value")

我的期望:

>>> _list
[['value'], [], [], [], [], [], []]

我得到了什么:

>>> _list
[['value'], ['value'], ['value'], ['value'], ['value'], ['value'], ['value']]

这是为什么?我怎么能绕过它?

1 个答案:

答案 0 :(得分:4)

您的问题是您的列表不包含七个独立列表,而是七次相同列表。

要创建列表列表,最好使用列表解析:

_list = [[] for _ in xrange(7)]

将生成包含七个不同列表的列表。