问题与弹出()和append()
任何帮助将不胜感激!问题与弹出()和append()
res = []
s = [1,2,3,4,5,6]
s.pop()
res.append(s)
print res
s.pop()
res.append(s)
print res
上面的Python代码提供了以下结果
[[1, 2, 3, 4, 5]]
[[1, 2, 3, 4], [1, 2, 3, 4]]
我不明白为什么上的流行会影响水库。我指的是打印结果应该是
[[1,2,3,4,5]]
[[1,2,3,4,5],[1,2,3,4]]
这是可以的 - 因为res会保持不变作为s(对同一个对象 - 在这个例子中是数组)。
为了解决这个问题,利用这个:
res = []
s = [1,2,3,4,5,6]
s.pop()
res.append(list(s))
print res
s.pop()
res.append(list(s))
print res
也看看:
python: Appending a dictionary to a list - I see a pointer like behavior
感谢您的参考链接@ Dozon Higgs – n00d1es
在Python,每个值都是一个参考(指针)的一个对象。 赋值总是复制值(这是一个指针);两个这样的指针可以指向同一个对象。
为了获得所需的结果,你需要复制的初始列表:
res = []
s = [1,2,3,4,5,6]
s.pop()
res.append(s[:])
print(res)
s.pop()
res.append(s[:])
print(res)
同样可以使用list.copy()
函数来完成:
...
res.append(s.copy())
...
输出:
[[1, 2, 3, 4, 5]]
[[1, 2, 3, 4, 5], [1, 2, 3, 4]]
谢谢@RomanPerekhrest。现在我明白了。 – n00d1es
你与*同一列表的工作*。你已经将's'添加到'res' *两次*,但它仍然是**相同的列表** –
在添加s到res之前,我弹出s中的最后一项。所以res中的两项应该是不同的,对吧? – n00d1es