简体   繁体   English

附加到原始列表时,嵌套列表的副本会变大

[英]Copy of nested list gets bigger when appending to original

I encountered a problem in this code snippet:我在这段代码片段中遇到了一个问题:

temp = matrixInput.copy()
for iy in range(len(temp)):
    for runde in range(1, 5):
        for ix in temp[iy]:
            print("iy:", iy, "ix:", ix, "runde", runde, "len:", len(temp[iy]))
            newnumber = ix + runde
            if newnumber > 9:
                newnumber -= 9
            matrixInput[iy].append(newnumber)

matrixInput is a list of lists (matrix if you want) with a whole bunch of integers. matrixInput是一个包含一大堆整数的列表(如果需要,可以使用矩阵)。

The idea is to create a copy, iterate over the copy and append to the original.这个想法是创建一个副本,将副本和 append 迭代到原始副本。 Do this 4 times and every time the value in the appended number should increase by 1. The goal is to get a matrix 5 times as big as initial.这样做 4 次,每次附加数字中的值应该增加 1。目标是得到一个 5 倍于初始值的矩阵。

So far so good.到目前为止,一切都很好。 But for some reason when I append to matrixInput the most inner loop gets stuck and endlessly appends.但是由于某种原因,当我 append 到matrixInput时,最内部的循环卡住并无休止地追加。 temp[iy] actually gets bigger and bigger despite me appending to matrixInput[iy] .尽管我附加到matrixInput[iy] ,但temp[iy]实际上变得越来越大。 What is my mistake?我的错误是什么?

as mentioned in the comment list.copy() is shallow, a solution would be to use the deepcopy method from copy library正如评论中提到的 list.copy() 是浅的,一个解决方案是使用复制库中的 deepcopy 方法

import copy
...
temp=copy.deepcopy(matrixInput)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM