Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 你的行为奇怪吗?_Python_List - Fatal编程技术网

Python 你的行为奇怪吗?

Python 你的行为奇怪吗?,python,list,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, 2, 3, 4], [1, 2, 3, 4], [1, 2

对于
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, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
循环运行时,每次所有数组元素都替换为plugh1的值

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

这个:

plugh2.append(plugh1)
附加对
plugh1
的引用,而不是副本。这意味着未来的更新将反映在
plugh2
中。如果需要副本,请参见此处:

此:

plugh2.append(plugh1)

附加对
plugh1
的引用,而不是副本。这意味着未来的更新将反映在
plugh2
中。如果需要副本,请参见此处:

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

print(pligh2[0] is pligh2[1])
#: True
列表中的每个元素都是其他元素,因为它们都是相同的对象

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

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

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

print(pligh2[0] is pligh2[1])
#: True
列表中的每个元素都是其他元素,因为它们都是相同的对象

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

plugh2.append(plugh1[:])
# or
plugh2.append(plugh1.copy())
当你这样做的时候

plugh2.append(plugh1)
您实际上是在向第一个列表添加引用,而不是当前的列表。所以下次你做的时候

plugh1.append(n)
您也在更改plugh2中的内容

你可以像这样复制列表,这样之后它就不会改变了

plugh2.append(plugh1[:])
当你这样做的时候

plugh2.append(plugh1)
您实际上是在向第一个列表添加引用,而不是当前的列表。所以下次你做的时候

plugh1.append(n)
您也在更改plugh2中的内容

你可以像这样复制列表,这样之后它就不会改变了

plugh2.append(plugh1[:])

也可以只做
plugh2.append(plugh1[:])
非常好。谢谢你帮助新手。Cheers还可以做
plugh2.append(plugh1[:])
非常好。谢谢你帮助新手。干杯