我正在尝试计算这个嵌套组合字典列表中的“名称”键,我得到 3 而不是 6,我认为我的问题是递归函数 count_elem(tree) 中的基本情况
def define_tree3():
tree3 ={'name':'GAS','grade':0.8,'children':[{'name':'CSA','grade':0.5,'children':[{'name':'MB','grade':0.1},{'name':'TA','grade':0.6}]},{'name':'IIW','grade':0.9,'children':[None,{'name':'IP','grade':0.99}]}]}
return tree3
#this fuction is to delete the given key from the given dict and retur the new dict
def delkey(dict1,key):
d=dict(dict1)
del d[key]
return d
#this function is to count the numbers of 'name'
def count_elem(tree):
if len(tree)==0:
return 0
else:
for i in tree:
if i == None:
return 0
elif i == 'name':
return 1+ count_elem(delkey(tree,i))
elif i == 'grade':
return count_elem(delkey(tree,i))
elif i == 'children':
for j in tree[i]:
if j == None:
continue
else:
return count_elem(j)
a=define_tree3()
print(count_elem(a))
红糖糍粑
相关分类