计算嵌套组合字典列表中相同键的函数

我正在尝试计算这个嵌套组合字典列表中的“名称”键,我得到 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))


慕慕森
浏览 115回答 1
1回答

红糖糍粑

这不是您问题的答案。我只是尝试解决它并使用了不同的方法。作为参考可能有用。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}]}]}def count_name(entity):    count = 0    name = 'name'    # print('\n')    # print(count, entity)    if type(entity) == dict:        count += sum([key == name for key in entity.keys()])            for value in entity.values():            # print(count, value)            if type(value) == list:                count += sum([count_name(member) for member in value])    return countcount_name(tree3)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python