Python的追加行为奇怪吗? [英] Python append behaviour odd?

查看:96
本文介绍了Python的追加行为奇怪吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've encountered what I think is odd behaviour for the append() function, and I've managed to duplicate it in the following simplified code:

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的值.

As the loop runs, each time all array elements are replaced with the value of plugh1.

在SO上也有类似的问题,但是解决方案似乎与嵌套函数和在这些调用之外定义变量有关.我认为这要简单得多.我想念什么?

There is a similar question on SO but the solution seems related to nesting functions and defining a variable outside of those calls. This is much simpler I think. What am I missing?

推荐答案

执行时

plugh2.append(plugh1)

您实际上是将引用附加到第一个列表,而不是当前列表.因此,下次您这样做

you are actually appending a reference to the first list, not the list as it currently is. Therefore the next time you do

plugh1.append(n)

您也正在更改plugh2中的内容.

you are changing the contents inside plugh2, as well.

您可以像这样复制列表,这样以后就不会更改.

You could copy the list like so, so that it doesn't change afterwards.

plugh2.append(plugh1[:])

这篇关于Python的追加行为奇怪吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆