Python 更新不同的变量而不是分配的参考变量

Python updating different variable instead of assigned reference variable

解决方案:test_dict = copy.deepcopy(DICT) 谢谢你们,我的游戏伙伴们。愿调试的轻松在未来成为你的恩典。

我创建了一个字典的副本,我将更改附加到新变量。 更改出现在旧变量中。

CHARACTERS = ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A']
DICT = {'key1': "foo", 'key2': "bar", 'key3': CHARACTERS}

def test(self):
    test_dict = DICT.copy()  # first reference of 'test_dict'
    print("DICT before", DICT)
    test_dict['sequence'] += ['G']
    print("DICT after ", DICT)

输出:

DICT before {'key1': "foo", 'key2': "bar", 'key3': ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A']}
DICT after  {'key1': "foo", 'key2': "bar", 'key3': ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A', 'G']}

字母 'G' 附加到 DICT 和 test_dict。

完全是恶作剧,如果你问我的话。

更新:我尝试了建议的:test_dict = DICT.copy() 但没有成功。我在上面包含这个的更新代码中做错了什么?

您创建的不是副本,而是参考。两个变量都指向相同的内存区域。如果你想创建不改变“原件”的精确副本,你应该使用 test_dict = DICT.copy()。这会创建一个浅拷贝(不复制嵌套 dicts/lists)。为了解决这个问题,需要一个深拷贝。一种获取方法是使用 copy 模块

中的 copy.deepcopy 函数
import copy

CHARACTERS = ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A']
DICT = {'key1': "foo", 'key2': "bar", 'key3': CHARACTERS}

def test():
    test_dict = copy.deepcopy(DICT) # first reference of 'test_dict'
    print("DICT before", DICT)
    test_dict['key3'] += ['G']
    print("DICT after ", DICT)

test()

这按预期输出:

DICT before {'key1': 'foo', 'key2': 'bar', 'key3': ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A']}
DICT after  {'key1': 'foo', 'key2': 'bar', 'key3': ['A', 'G', 'T', 'C', 'C', 'A', 'G', 'T', 'G', 'T', 'A', 'A']}