附加到列表列表中的嵌套列表

时间:2013-10-17 15:13:03

标签: python list python-2.7

考虑这个例子:

>>> result = [[]] * 8
>>> result
[[], [], [], [], [], [], [], []]
>>> result[0]
[]
>>> result[0].append("foo")
>>> result  # wtf? expected result: [['foo'], [], [], [], [], [], [], []]
[['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo']]

我对此感到非常困惑。也许我不明白如何使用append。我如何附加到列表中列出的i嵌套?

1 个答案:

答案 0 :(得分:4)

这是因为,通过这样做:

result = [[]] * 8

您制作相同列表的8 。你的代码应该是:

>>> result = [[] for _ in xrange(8)]
>>> result
[[], [], [], [], [], [], [], []]
>>> result[0]
[]
>>> result[0].append("foo")
>>> result
[['foo'], [], [], [], [], [], [], []]
>>>

作为证明,请考虑一下:

>>> lst = [[]] * 2
>>> lst
[[], []]
>>> id(lst[0])
28406048
>>> id(lst[1])
28406048
>>>

请注意,列表的ID与此处的ID相同:

>>> lst = [[] for _ in xrange(2)]
>>> lst
[[], []]
>>> id(lst[0])
28408408
>>> id(lst[1])
28418096
>>>

他们是不同的。