Skip to main content
 首页 » 编程设计

python之字典中的递归

2025年04月02日13mate10pro

我有一个嵌套的 dict,如下所示:

键 children 中有多个嵌套。每当出现 key children 时,我都想捕获 key branch 。因为有多个 children,所以我想为每个 child 都这样做。当然,每个 child 还可以有更多的 child 。这种嵌套最多可以达到 7 层。

为了实现这一点,我可以编写一个愚蠢的 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 个级别。

我怎样才能改进它以获得所有级别?

如有任何指点,我们将不胜感激。

请您参考如下方法:

你有一些不必要的冗余。如果我理解正确的话,您需要将句柄与递归分开添加到列表中,因为您想在父级中测试 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'] 的长度——如果它为零,那么循环将不会执行任何操作。