2013-10-17 63 views
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嵌套列表中?

+1

请参阅[本问题](http://stackoverflow.com/questions/19427735/where-goes-wrong-in-this-list-manipulation/19427770#19427770)。 – mdml

+1

您正在复制对同一列表的引用。 '结果[0]'与'result [1]','result [2]'等是相同的对象。 –

+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是因为在这些地方一样:

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

它们是不同的。