【问题标题】:python pointer error: unexpected variable mutationpython指针错误:意外的变量突变
【发布时间】:2015-07-28 05:58:59
【问题描述】:
def divide_grid():
    G = [[1, 'p'], [2, 'g'], [3, 'r'], [4, 'p']]
    print(G)
    for color in ['p','g']:  
        lst = G
        process(lst)
        print(G)

def process(grid):
    grid[0][1] = 'g'

我在python中有这段代码,当我运行它时,我希望G保持不变(同样的东西应该打印3次。)我的印象是python没有使用指向变量的指针?但是,当我运行 divide_grid() 时,我得到了这个:

[[1, 'p'], [2, 'g'], [3, 'r'], [4, 'p']]
[[1, 'g'], [2, 'g'], [3, 'r'], [4, 'p']]
[[1, 'g'], [2, 'g'], [3, 'r'], [4, 'p']]

为什么会这样?如何修复它,以便我可以在不更改原始 G 的情况下编辑网格的进程版本?这是我的代码的淡化版本,为了让它工作,我需要能够从这个过程函数编辑和返回网格而不改变原始的。

【问题讨论】:

    标签: python list pointers recursion mutators


    【解决方案1】:

    当你将 G 赋值给 lst 时,它是一个指针。

    你需要使用 deepcopy 来避免这种情况:

    from copy import deepcopy
    lst = deepcopy(G)
    

    【讨论】:

    • 只有deepcopy 可以在这里工作,因为列表列表copy.copy and [:] 在这里不能工作
    猜你喜欢
    • 2015-10-13
    • 2019-11-07
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2020-06-29
    相关资源
    最近更新 更多