2013-12-18 49 views
1

我已經使用Python好幾年了,但只是注意到一個非常令人困惑的事情。區別(3)中[[]] * 3和[[]]之間的區別]

a=[[]]*3 
a[0].append(3) 

a=[[] for i in range(3)] 
a[0].append(3) 

不具有同樣的效果,即使型(名單)是一樣的。 第一個收益a=[[3], [3], [3]],第二個a=[[3],[],[]](如預期)。

有沒有人有解釋?

+3

這麼多的重複... – wim

+1

@jonrsharpe這是如此接近一個確切的複製它只是吹了我的腦海! – SethMMorton

+3

問題是_重複。這是一個重複的? –

回答

9

[[]]*3創建一個具有三個引用到同一個列表對象的列表:

>>> lst = [[]]*3 
>>> # The object ids of the lists in 'lst' are the same 
>>> id(lst[0]) 
25130048 
>>> id(lst[1]) 
25130048 
>>> id(lst[2]) 
25130048 
>>> 

[[] for i in range(3)]創建一個具有三個獨特名單對象的列表:

>>> lst = [[] for i in range(3)] 
>>> # The object ids of the lists in 'lst' are different 
>>> id(lst[0]) 
25131768 
>>> id(lst[1]) 
25130008 
>>> id(lst[2]) 
25116064 
>>> 
+0

這很有道理,謝謝! – user3117090

相關問題