我有一个名为ones的列表,它在一段不应影响它的代码块之后改变值.为什么?
s = 3
ones = []
terms = []
for i in range (0, s):
ones.append(1)
terms.append(ones)
print(terms)
twos = []
if len(ones) > 1:
twos.append(ones)
twos[-1].pop()
twos[-1][-1] = 2
print(twos)
print(terms)
输出:
[[1, 1, 1]] # terms
[[1, 1, 2]] # twos
[1, 1, 2] # terms
对于上下文,我试图用这个开始解决这个英国信息学奥林匹克过去考试第7页的问题:http://www.olympiad.org.uk/papers/2009/bio/bio09-exam.pdf.
最佳答案 这里:
twos.append(ones)
您正在追加对一个的引用,而不是它的值.看到不同:
In [1]: l1 = [1, 2, 3]
In [2]: l2 = []
In [3]: l2.append(l1)
In [4]: l2, l1
Out[4]: ([[1, 2, 3]], [1, 2, 3])
In [5]: l2[0][1] = 'test'
In [6]: l2, l1
Out[6]: ([[1, 'test', 3]], [1, 'test', 3])
为了避免这种情况,您可以使用[:]运算符来复制:
In [7]: l1 = [1, 2, 3]
In [8]: l2 = []
In [9]: l2.append(l1[:])
In [10]: l2, l1
Out[10]: ([[1, 2, 3]], [1, 2, 3])
In [11]: l2[0][1] = 'test'
In [12]: l2, l1
Out[12]: ([[1, 'test', 3]], [1, 2, 3])