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

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]]‍♂️ 这意味着代码仍在更新原始列表 e.i: 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