Python附加行为奇怪?

时间:2016-09-14 04:30:58

标签: python list

我遇到了我认为append()函数的奇怪行为,我设法在以下简化代码中复制它:

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的值替换所有数组元素时。

在SO上有类似的问题,但解决方案似乎与嵌套函数和在这些调用之外定义变量有关。我认为这更简单。我错过了什么?

3 个答案:

答案 0 :(得分:2)

当你这样做时

plugh2.append(plugh1)

您实际上是在追加第一个列表的引用,而不是当前列表。因此,下次你做

plugh1.append(n)

你也在改变plugh2里面的内容。

您可以像这样复制列表,以便之后不会更改。

plugh2.append(plugh1[:])

答案 1 :(得分:1)

发生这种情况的原因是您没有复制列表本身,而只复制列表的引用。尝试运行:

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

列表中的每个元素“都是”所有其他元素,因为它们都是相同的对象。

如果您想自己复制此列表,请尝试:

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

答案 2 :(得分:0)

此:

plugh2.append(plugh1)

追加plugh1的引用,而不是副本。这意味着未来的更新会反映在plugh2中。如果您需要副本,请参阅此处:https://docs.python.org/2/library/copy.html

相关问题