考虑这个例子:
>>> result = [[]] * 8
>>> result
[[], [], [], [], [], [], [], []]
>>> result[0]
[]
>>> result[0].append("foo")
>>> result # wtf? expected result: [['foo'], [], [], [], [], [], [], []]
[['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo']]
我对此感到非常困惑。也许我不明白如何使用append
。我如何附加到列表中列出的i
嵌套?
答案 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
>>>
他们是不同的。