[英]Changing second-to-last entry in list changes all preceding entries
The code I'm trying to write includes for loops that fill in a list in reverse order: The last entry is set first, and then the t-th entry is set based on the (t+1)th entry, iterating backwards until it gets to the 0th entry. 我正在尝试编写的代码包括for循环,这些循环以相反的顺序填充列表:首先设置最后一个条目,然后根据第(t + 1)个条目设置第t个条目,向后迭代直到它到达第0个条目。 Unfortunately, I kept the getting the strange problem of all the entries before the 2nd-to-last being equal to the 2nd-to-last.
不幸的是,我一直在碰到倒数第二个等于倒数第二个所有条目的奇怪问题。
Strangely enough, I managed to reproduce the problem even without the for loop. 奇怪的是,即使没有for循环,我也设法重现了问题。
The entries in this example are lists of length 3 because that's how it is in my real work. 此示例中的条目是长度为3的列表,因为在我的实际工作中就是这样。 The problem goes away if I just make the entries ints.
如果我仅将条目设置为int,问题就消失了。
def bet(p):
bet=[[0,0,0]]*p
bet_end=[]
for k in range(0,3):
bet_end.append(1)
bet[p-1]=bet_end
for k in range(0,3):
bet[p-2][k]=2
return bet
test=bet(5)
I expect the output to be 我希望输出是
[[0,0,0],[0,0,0],[0,0,0],[2,2,2],[1,1,1]]
Instead, I get 相反,我得到
[[2,2,2],[2,2,2],[2,2,2],[2,2,2],[1,1,1]]
Why did the 0th, 1st and 2nd entries get affected by the change to the 3rd entry? 为什么第3个条目的更改会影响第0,第1和第2个条目?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.