美文网首页
解决:python 递归结束时,储存的中间变量消失了

解决:python 递归结束时,储存的中间变量消失了

作者: 辘轳鹿鹿 | 来源:发表于2021-11-25 15:20 被阅读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博客

    原来 image.png

    这一行直接复制就可以了

    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()
    

    相关文章

      网友评论

          本文标题:解决:python 递归结束时,储存的中间变量消失了

          本文链接:https://www.haomeiwen.com/subject/yqaatrtx.html