亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算嵌套組合字典列表中相同鍵的函數

計算嵌套組合字典列表中相同鍵的函數

慕慕森 2023-10-26 14:38:40
我正在嘗試計算這個嵌套組合字典列表中的“名稱”鍵,我得到 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 dictdef 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))
查看完整描述

1 回答

?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

這不是您問題的答案。我只是嘗試解決它并使用了不同的方法。作為參考可能有用。


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 count


count_name(tree3)


查看完整回答
反對 回復 2023-10-26
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號