list.copy()未创建真实副本

时间:2019-05-31 02:32:07

标签: python python-3.x

我正在尝试编写一些代码来完成关于代码战link的练习

我要做的一部分工作是遍历代表数独网格的列表列表,并用可能的数字列表替换0。

我的问题是,即使我使用list.copy()来保存原始拼图,我对原始列表(而非副本)所做的任何更改仍会更改副本。

这怎么可能?

下面是我的代码:

def sudoku(puzzle):

    # copy the puzzle to be able to save original positions that are changeable 
    pc = puzzle.copy()

    puzzle = pns(puzzle)

    return puzzle



def pns(puzzle): 
    for y in range(len(puzzle)):
        for x in range(len(puzzle[0])):

            pn = set(range(1,len(puzzle) + 1))

            for row_idx in range(len(puzzle)):
                for col_idx in range(len(puzzle[row_idx])):

                    skip_bool = True
                    if puzzle[y][x] != 0 and type(puzzle[y][x]) == type(1):
                        skip_bool = False

                    if row_idx == y and col_idx != x and type(puzzle[row_idx][col_idx]) != type([0]):
                        if puzzle[row_idx][col_idx] in pn:
                            pn.remove(puzzle[row_idx][col_idx])

                    if col_idx == x and row_idx != y and type(puzzle[row_idx][col_idx]) !=  type([0]):
                        if puzzle[row_idx][col_idx] in pn:
                            pn.remove(puzzle[row_idx][col_idx])
            pn = list(pn)

            if len(pn) == 1:
                puzzle[y][x] = pn[0]

            elif len(pn) == 0:
                puzzle[y][x] = False

            elif skip_bool:
                puzzle[y][x] = pn

    return puzzle

预期的输出:

print(pc)
print(puzzle)

[5, 3, 0, 0, 7, 0, 0, 0, 0]
[6, 0, 0, 1, 9, 5, 0, 0, 0]
[0, 9, 8, 0, 0, 0, 0, 6, 0]
[8, 0, 0, 0, 6, 0, 0, 0, 3]
[4, 0, 0, 8, 0, 3, 0, 0, 1]
[7, 0, 0, 0, 2, 0, 0, 0, 6]
[0, 6, 0, 0, 0, 0, 2, 8, 0]
[0, 0, 0, 4, 1, 9, 0, 0, 5]
[0, 0, 0, 0, 8, 0, 0, 7, 9]

[5, 3, [1, 2, 4, 6, 9], [2, 6, 9], 7, [1, 2, 4, 6, 8], [1, 4, 6, 8, 9], [1, 2, 4, 9], [2, 4, 8]]
[6, [2, 4, 7, 8], [2, 3, 4, 7], 1, 9, 5, [3, 4, 7, 8], [2, 3, 4], [2, 4, 7, 8]]
[[1, 2, 3], 9, 8, [2, 3, 5, 7], [3, 4, 5], [1, 2, 4, 7], [1, 3, 4, 5, 7], 6, [2, 4, 7]]
[8, [1, 2, 4, 5, 7], [1, 2, 4, 5, 7, 9], [2, 5, 7, 9], 6, [1, 2, 4, 7], [1, 4, 5, 7, 9], [1, 2, 4, 5, 9], 3]
[4, [2, 5, 7], [2, 5, 6, 7, 9], 8, 5, 3, [6, 7, 9], [2, 9], 1]
[7, [1, 4, 5, 8], [1, 3, 4, 5, 9], [3, 5, 9], 2, [1, 4, 8], [1, 3, 4, 5, 8, 9], [1, 3, 4, 5, 9], 6]
[[1, 3, 9], 6, [1, 3, 4, 5, 7, 9], [3, 5, 7, 9], [3, 4], [1, 4, 7], 2, 8, [4, 7]]
[[2, 3], [2, 7, 8], [2, 3, 6, 7], 4, 1, 9, [3, 6, 7, 8], [2, 3], 5]
[[1, 2, 3], [1, 2, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 5, 6], 8, [1, 2, 4, 6], [1, 3, 4, 5, 6], 7, 9]

我实际上得到的是第二个列表的2个副本。

1 个答案:

答案 0 :(得分:0)

对于嵌套结构,.copy()仅将创建顶级对象的副本,但是其中包含的引用仍将是相同的引用。

您可能想要copy.deepcopy()