多di中的python递归

2024-09-09 13:05:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在递归中遇到了多个dict的问题, 源非递归代码是

mylist = (["AA","BB","CC","DD"])
tempdict = dict()
n = len(mylist)
for j in range(0 , n ):
    if j == 0:
        if mylist[j] not in tempdict:
            tempdict[mylist[j]] = "1"
    if j == 1:
        if mylist[j] not in tempdict[mylist[0]]:
            tempdict[mylist[0]] = dict()
            tempdict[mylist[0]][mylist[1]] = "1"
    if j == 2:
        if mylist[j] not in tempdict[mylist[0]][mylist[1]]:
            tempdict[mylist[0]][mylist[1]] = dict() 
            tempdict[mylist[0]][mylist[1]][mylist[2]] = "1"
    if j == 3:
        .......
    if j == 4:
        .......
    if j == n:
        .......
print tempdict

结果:{'AA'{'BB':{CC':{'DD':'1'}}}} 当我需要用dict()构建一个多密钥时,它是有效的。 然而,这是不可能列出所有的。 所以我想在递归函数中细化代码

^{pr2}$

结果: {'AA':'1'}

但不是我的结果 请帮我找出递归代码中的错误, 谢谢大家。在


Tags: 代码inforlenifnotrangedict
2条回答

给你。在

def rfun(tmpdict, mylist, idx, listlen):
    if idx < listlen:
        if idx == listlen - 1: # for last element in mylist
            tmpdict[mylist[idx]] = "1"
        else:
            tmpdict[mylist[idx]] = {}
            rfun(tmpdict[mylist[idx]], mylist, idx + 1, listlen)

newdict = {}
mylist = ["AA","BB","CC","DD"]
rfun(newdict, mylist, 0, len(mylist))
print newdict

关键思想是,如果元素不是最后一个,则将新创建的字典传递给下一个递归函数调用。在

mylist = ["AA","BB","CC","DD"]

递归版本简洁,但在极端情况下可能会导致堆栈溢出:

^{pr2}$

结果:{AA':{BB':{CC':{DD':'1'}}}

非递归版本可以通过反向循环列表并执行以下操作来完成相同的操作:

^{pr3}$

但是需要复制列表才能反转列表(这应该比递归更有效)。通过索引进行迭代也可以使用^{{cd1>}

相关问题 更多 >