使字典充当递归函数的局部变量

Make dictionary act as local variable for recursive function

我有一个以字典作为参数的递归函数, 该函数在调用自身之前更改字典。我希望字典的更改只影响被调用的函数,而不会影响作用域之外的任何东西。

我可以创建本地词典吗?

dict = {10 : 5, 20 : 5}

def recursive_func(dict_arg, total_arg):
    dict_local = dict_arg

    for k, v in dict_local.items():
        total = total_arg + k
        if total >= 25:
            dict_local.update({k : v -1})
            print(str(total) + str(dict_local))
        else:
            dict_local.update({k : v -1})
            recursive_func(dict_local, total)

print("dict before func: " + str(dict))
recursive_func(dict, 0)
print("dict after func: " + str(dict))


terminal >>>
dict before func: {10: 5, 20: 5}
30{10: 2, 20: 5}
40{10: 2, 20: 4}
30{10: 2, 20: 3}
30{10: 1, 20: 2}
40{10: 1, 20: 1}
dict after func: {10: 1, 20: 1}

可以看出,函数执行后字典发生了变化,打印出的总数与字典中剩余的10和20的对应数量不匹配。

查看 copy() 运算符。你可能不需要 deepcopy() 这里。

https://docs.python.org/2/library/copy.html

您可以使用以下代码:

test_dict = {10 : 5, 20 : 5}

def recursive_func(dict_arg, total_arg):
    dict_local = test_dict.copy()

    for k, v in dict_local.items():
        total = total_arg + k
        if total >= 25:
            dict_local.update({k : v -1})
            print(str(total) + str(dict_local))
        else:
            dict_local.update({k : v -1})
            recursive_func(dict_local, total)

print("dict before func: ", str(test_dict))
recursive_func(test_dict, 0)
print("dict after func: ", str(test_dict))

生产:

dict before func:  {10: 5, 20: 5}
30{10: 4, 20: 5}
40{10: 4, 20: 4}
30{10: 4, 20: 4}
30{10: 4, 20: 5}
40{10: 4, 20: 4}
dict after func:  {10: 5, 20: 5}

你需要对你的字典做一个深拷贝,否则它只会被引用,每次对副本的修改都会改变原始字典。

import copy

dict_local = copy.deepcopy(dict_arg)

这应该有效。正如 Jerry M. 指出的那样,您可能不需要深层复制,因为您的字典值只是整数。 copydeepcopy 之间的区别参见 this 例如。

dict = {10 : 5, 20 : 5}

def recursive_func(dict_arg, total_arg):

    for k, v in dict_arg.items():
        dict_local = dict_arg.copy()
        total = total_arg + k
        if total >= 25:
            dict_local.update({k : v -1})
            print(str(total) + str(dict_local))
        else:
            dict_local.update({k : v -1})
            recursive_func(dict_local, total)

print("dict before func: ", str(dict))
recursive_func(dict, 0)
print("dict after func: ", str(dict))


>>>
dict before func:  {10: 5, 20: 5}
30{10: 2, 20: 5}
40{10: 3, 20: 4}
30{10: 4, 20: 4}
30{10: 4, 20: 4}
40{10: 5, 20: 3}
dict after func:  {10: 5, 20: 5}