di中的递归

2024-10-02 20:30:15 发布

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

我有一个嵌套的dict,看起来像这样:

enter image description here

在键children中有多个嵌套。只要存在键children,我就会捕获该键branch。因为有多个children,我想为每个孩子做这个。当然,每个孩子还可以有更多的children。这种嵌套可以达到7级。你知道吗

为了实现这一点,我可以编写一个boneheaded 7-for循环方法,也可以使用递归。所以我给了递归一个机会,产生了以下代码:

def GatherConcepts(header):
    if 'children' in header.keys():
        if len(header['children']) > 0:
            if 'branch' in header.keys():
                concepts.append(header['handle'])
                if 'children' in header.keys():
                    for j in range(0, len(header['children'])):
                        GatherConcepts(header['children'][j])
            else:
                for i in range(0,len(header['children'])):
                    GatherConcepts(header['children'][i])

这段代码的问题是,它只给了我2个级别(因为我调用函数本身2次,因此没有正确地使用递归),而不是7级。你知道吗

我怎样才能提高这个水平呢?你知道吗

如有任何提示,我们将不胜感激。你知道吗


Tags: 方法代码inbranchforlenif孩子
2条回答

为了正确地获取递归,可以使用以下简单模板:

def recursive(variable):
    if something:
        # base step
        return somethingelse
    else:
        # recursive step
        return recursive(somethingelse)

在您的情况下,您可以尝试以下操作:

def gather_concepts(header):
    # recursive step
    if 'branch' in header and 'handle' in header:
        concepts.append(header['handle'])
    if 'children' in header:
        for child in header['children']:
            return gather_concepts(child)
    # base step
    else:
        return

不过,您应该根据自己的需要调整此代码,因为我还没有亲自测试过它。你知道吗

你有一些不必要的裁员。如果我理解正确,您需要将句柄与递归分别添加到列表中,因为您希望在父级中测试branch。你知道吗

def GatherConcepts(header):
    if 'children' in header and 'branch' in header:
        for child in header['children']:
            concepts.append(child['handle'])
            GatherConcepts(child)

您不需要测试header['children']的长度,如果它是零,那么循环就什么也不做了。你知道吗

相关问题 更多 >