【发布时间】: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