python - 在递归函数中复制 python 中的列表对象 - 奇怪的行为

标签 python list recursion

这个递归函数:

myGrid = [[0,0,0],
          [0,0,0],
          [0,0,0]]

def testchange(grid, number=-1, number2=0):
    kgrid = list(grid)
    kgrid[number][number2] = 2
    number += 1
    number2 += 1
    if number < 2:
        print '1', kgrid
        testchange(kgrid,number,number2)
        print '2', kgrid
        testchange(kgrid,number+1,number2)

testchange(myGrid);

打印输出:

1 [[0, 0, 0], [0, 0, 0], [2, 0, 0]]
1 [[0, 2, 0], [0, 0, 0], [2, 0, 0]]
2 [[0, 2, 0], [0, 0, 2], [2, 0, 0]]
2 [[0, 2, 0], [0, 0, 2], [2, 0, 2]]

在我第一次调用 testchange() 之后,我的函数中的 kgrid 不应更改,但正如您所看到的,为什么?

最佳答案

要复制网格,请使用 copy.deepcopy() 。否则会进行浅复制,从而导致您所描述的行为。

关于python - 在递归函数中复制 python 中的列表对象 - 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14538283/

相关文章:

python libtorrent save_state

python - 我尝试使用我安装的 python 包,但出现此错误

apache-flex - Flex 选定的项目问题

c# - 在 C# 中使用 List<> 作为 BindingSource

将递归 C 函数转换为 ARM 程序集?

python - 如何停止无限 while 循环 python emacs

python - 如何按索引合并两个列表

python - 与常规循环相比,递归有什么优势?

C++ - 递归函数中的字符串流

python - 使用 python3 访问 Google Sheets 上的电子表格