【问题标题】:python recursive in multiple dictpython在多个dict中递归
【发布时间】:2014-06-26 03:43:28
【问题描述】:

我在递归中遇到了多个 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() 构建多个键时,它就可以工作。 但是,不可能全部列出。 所以我想在递归函数中优化代码

def rfun(tmpdict, mylist, idx, listlen):
    if idx < listlen:
        if idx == 0:
            if mylist[idx] not in tmpdict:
                tmpdict[mylist[idx]] = "1"
            rfun(tmpdict [mylist[idx]], list, idx + 1, listlen)
        else:
            if list[idx] not in tmpdict:
                tmpdict = dict()
                tmpdict [mylist[idx]] = "1"
            rfun(tmpdict [mylist[idx]], mylist, idx + 1, listlen)

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

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

但是,结果出乎我的意料,
请帮我找出我的递归代码有什么问题, 谢谢大家。

【问题讨论】:

  • 你的rfun没有回报,有什么遗漏吗?

标签: python recursion dictionary


【解决方案1】:

给你。

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

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

【讨论】:

    【解决方案2】:
    mylist = ["AA","BB","CC","DD"]
    

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

    def l2rd(*args):
       return  { args[0] : (len(args)>1) and l2rd(*args[1:]) or "1" }
    
    result = l2rd(*mylist)
    print(result)
    

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

    非递归版本可以通过以相反的顺序循环列表并执行以下操作来做同样的事情:

    curr = "1"
    for key in reversed_list:
       curr = { key : curr }
    return curr
    

    但是那个需要复制列表才能反转它(这仍然应该比递归更有效)。通过索引进行迭代也可以使用range(len(args)-1,-1,-1)

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 2020-07-09
      • 2013-08-30
      • 2021-08-27
      相关资源
      最近更新 更多