我遇到什么,我认为是对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的值。
关于被如此类似的问题,但解决方案似乎与嵌套功能和定义这些电话以外的变量。我认为这很简单。我错过了什么?
还可以'plugh2.append(plugh1 [:])' – sberry
优秀。感谢您帮助newb。干杯 –