0

考虑这个例子:

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

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

4

1 回答 1

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 与此处相同:

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

它们不一样。

于 2013-10-17T15:14:51.897 回答