简体   繁体   English

更改列表中倒数第二个条目会更改所有先前的条目

[英]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个条目?

Change this line 更改此行

bet=[[0,0,0]]*p

to, 至,

bet=[[0,0,0] for i in range(p)]

Output: 输出:

>>> bet(5)
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [2, 2, 2], [1, 1, 1]]

Why? 为什么?

Read here to know how to initialize lists properly. 阅读此处以了解如何正确初始化列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 按倒数第二个字符对字符串列表进行排序 - Sort a list of strings by second-to-last character 如何在控制台中的最后一行和倒数第二行之间打印? - How to print between last and second-to-last lines in console? Python通过比较倒数第二个到倒数第二个值 - Python add/subtract counter by comparing last to second-to-last values Python列表条目被最后附加的条目覆盖 - Python list entries are overridden by last appended entry 如何索引倒数第二个追加的行? Numpy和Python - How to index the second-to-last appended row? Numpy and Python 更改元组列表,以使第一个条目与第二个条目相同 - Changing a tuple list so that the first entry is the same as the second entry 为什么Processing.py会跳过我的数组的倒数第二项? - Why is Processing.py skipping the second-to-last item of my array? python:确定列表的所有条目是否在嵌套列表的条目内 - python: determine if all entries of a list are within entry of a nested list 更改列表的最后一个元素也会覆盖倒数第二个元素 - Changing the last element of a list also overwrites the second last element 取第一个和第二个中间条目,第二个和第二个中间条目的点积,直到中间1和最后一个条目python / numpy - Take dot product of first and middle entry, second and middle+1 entries until middle-1 and last entry python/numpy
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM