2016-09-14 131 views
0

我遇到什麼,我認爲是對append()功能奇怪的行爲,我已經成功地複製它在以下簡化代碼:Python追加行爲奇怪?

plugh1 = [] 
plugh2 = [] 
n = 0 
while n <= 4: 
    plugh1.append(n) 
    plugh2.append(plugh1) 
    n = n+1 
print plugh1 
print plugh2 

我希望造成這樣的代碼:

plugh1 = [1, 2, 3, 4] 
plugh2 = [[1], [1, 2], [1, 2, 3, ], [1, 2, 3, 4]] 

但實際結果是:

plugh1 = [1, 2, 3, 4] 
plugh2 = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] 

作爲循環運行中,每個所有數組元素與更換時間plugh1的值。

關於被如此類似的問題,但解決方案似乎與嵌套功能和定義這些電話以外的變量。我認爲這很簡單。我錯過了什麼?

回答

2

當你

plugh2.append(plugh1) 

你實際上是附加到第一個列表的引用,不就行,因爲它目前是。因此,下次你做

plugh1.append(n) 

你也改變了plugh2內的內容。

你可以複製列表像這樣,所以它不會改變之後。

plugh2.append(plugh1[:]) 
0

此:

plugh2.append(plugh1) 

追加參考plugh1,而不是一個副本。這意味着將來的更新反映在plugh2。如果你需要一個副本,在這裏看到:https://docs.python.org/2/library/copy.html

+5

還可以'plugh2.append(plugh1 [:])' – sberry

+0

優秀。感謝您幫助newb。乾杯 –

1

發生這種情況的原因是,你是不是複製列表本身,而只是引用到列表中。嘗試運行:

print(pligh2[0] is pligh2[1]) 
#: True 

列表中的每個元素都是「其他元素」,因爲它們都是相同的對象。

如果你想複製此列出自己,嘗試:

plugh2.append(plugh1[:]) 
# or 
plugh2.append(plugh1.copy())