gpt4 book ai didi

python - 如何在python递归函数中保留列表或字典?

转载 作者:行者123 更新时间:2023-11-28 18:51:02 27 4
gpt4 key购买 nike

我必须在 python 中使用递归函数,下面的代码是一个简化模型。我想在递归时保留result list和dict字典,不生成新的list或dictionary,递归后返回,如何解决?

def test(length):
result = []
dict = {}
if length == 10:
return result, dict
else:
result.append(length)
dict[length] = length + 1
test(length + 1)

x, y = test(0)
print x, y

最佳答案

使用执行递归的辅助函数,以及使用初始默认值调用辅助函数的 main 函数。

def test(length):
result = []
dict = {}
_test(length, result, dict)
return result, dict

def _test(length, result, dict):
if length == 10:
return
else:
result.append(length)
dict[length] = length + 1
_test(length + 1, result, dict)

x, y = test(0)
print x, y

关于python - 如何在python递归函数中保留列表或字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13114794/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com