繁体   English   中英

任何人都可以告诉我为什么在复制列表中更新时我的原始列表会更新?

[英]Anyone can tale me why my Original list updating when I Update in copied list?

这段代码给我 --> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ♂️ 这意味着代码仍在更新原始列表 ei: matrix2


matrix2 = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]

def changedItto_zero(col, row, column, arr):
    matrix_copy = arr[:] # --> copy list using slice , but it still updating 🤷‍♂️ the original list
    matrixLen_row = len(arr)
    matrixLen_col = len(arr[0])
    for row_index in range(0, matrixLen_row):
        for column_index in range(0, matrixLen_col):
            matrix_copy[row][column_index] = 0
            matrix_copy[row_index][column] = 0
    return matrix_copy



def change(arr):
    global col
    matrixLen_row = len(arr)
    matrixLen_col = len(arr[0])
    for row_index in range(0, matrixLen_row):
        for column_index in range(0, matrixLen_col):
            if(arr[row_index][column_index] == 0):
                find_row, find_column = row_index, column_index
                print('row ', find_row, ' col ', find_column)
               #  print('matx ', arr)
                col += 1
                finded = changedItto_zero(col, find_row, find_column, arr)
    return finded


print(change(matrix2))

# Right Output:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]

就像有人评论的那样,问题是arr[:]创建了arr列表的副本而不是其内容的副本。 您可以通过在创建副本后立即打印id(matrix_copy)id(arr)来确认这一点,它们应该显示不同的值,这意味着不同的列表。 但是如果你对每个列表的第一个元素( id(matrix_copy[0])id(arr[0]) )做同样的事情,你会发现它们是同一个列表。 这个问题的一个简单解决方案是显式创建深拷贝:

matrix_copy = copy.deepcopy(arr)  # You should import copy to use this function

暂无
暂无

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

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