如何在这个递归函数中计数?

2024-04-20 01:21:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想迭代嵌套字典(您可以在下面看到):

bsp = {'bewohnen': {'lemma': 'bewohnen', 'pos': 'VFIN', 'attributes': {'type': 'Full', 'person': '3', 'number': 'Pl', 'tense': 'Pres', 'mood': 'Ind'}},
       'bewirtschaften': {'lemma': 'bewirtschaften', 'pos': 'VFIN', 'attributes': {'type': 'Full', 'person': '3', 'number': 'Pl', 'tense': 'Pres', 'mood': 'Ind'}},
       'die': {'lemma': 'die', 'pos': 'ART', 'attributes': {'type': 'Def', 'case': 'Nom', 'number': 'Pl', 'gender': 'Masc'}}, 'vier': {'lemma': 'vier', 'pos': 'CARD', 'attributes': None},
       'Viertel': {'lemma': 'Viertel', 'pos': 'N', 'attributes': {'type': 'Nom', 'case': 'Nom', 'number': 'Pl', 'gender': 'Neut'}}}

#Code:

def iterdict(d, verbs={"all":0,"pres":0}):
        for k,v in d.items():

            if isinstance(v, dict):
               verbs = iterdict(v, verbs)
            elif k == "tense":
                verbs["all"]+= 1
                if v == "Pres":
                    verbs["pres"]+= 1
            return verbs


        return verbs["pres"]//verbs["all"]


print(iterdict(bsp))

我感兴趣的是计算字典中的结果(如果key得到“tense”,value得到“Pres”),也就是说,如果递归过程完成,返回的结果应该是

return verbs["pres"]//verbs["all"]

但是,当我看到它甚至不能正确计算时,“动词”字典保持在0/0。你知道吗

我的递归肯定出了问题,我是个初学者,只是不知道该怎么做才能完成。你知道吗


Tags: posnumberreturn字典typeallnomattributes
1条回答
网友
1楼 · 发布于 2024-04-20 01:21:27

下面有两种方法可以调用iterdict。如果在没有第二个参数的情况下调用它,它会将计数器对内部初始化为0。否则,它会改变给定的一对计数。你知道吗

iterdict的初始调用不带计数器。递归调用采用当前的一对计数,这些计数在递归调用中就地更新。每个递归调用的返回值实际上并不重要,因此可以忽略它。你知道吗

def iterdict(d, counts=None):
    if counts is None:
        counts = dict(all=0, pres=0)

    for k,v in d.items():

        if isinstance(v, dict):
            iterdict(v, counts)
        elif k == "tense":
            counts["all"] += 1
            if v == "Pres":
                counts["pres"] += 1


    return counts["pres"] // counts["all"]

相关问题 更多 >