2016-09-14 124 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())