解决:python 递归结束时,储存的中间变量消失了
2021-11-25 本文已影响0人
辘轳鹿鹿
写了一个递归函数,将一棵字典树的每一条分支解析出来,结果发现每次递归结束后,存储每一个分支的列表都突然变空
def tree_to_code(myTree,nodeTxt,rulelist,rulelib):
firstStr = list(myTree.keys())[0]
#print("*",firstStr)
rulelist.append(firstStr)
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[key]).__name__ == 'dict':
rulelist.append(key)
#print("**", key)
tree_to_code(secondDict[key], str(key),rulelist,rulelib)
else:
rulelist.append(key)
rulelist.append(secondDict[key])
rulelib.ruleset.append(rulelist)
print(rulelist)
rulelist.pop()
rulelist.pop()
if rulelist:
rulelist.pop()
if rulelist:
rulelist.pop()
参考了这个博主的文章
python 递归时存储中间变量要用copy 方法,否则出栈就废了_yyt200808的博客-CSDN博客
这一行直接复制就可以了
def tree_to_code(myTree,nodeTxt,rulelist,rulelib):
firstStr = list(myTree.keys())[0]
#print("*",firstStr)
rulelist.append(firstStr)
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[key]).__name__ == 'dict':
rulelist.append(key)
#print("**", key)
tree_to_code(secondDict[key], str(key),rulelist,rulelib)
else:
rulelist.append(key)
rulelist.append(secondDict[key])
rulecopy=rulelist.copy()
rulelib.ruleset.append(rulecopy)
print(rulelist)
rulelist.pop()
rulelist.pop()
if rulelist:
rulelist.pop()
if rulelist:
rulelist.pop()