我有一个嵌套的dict
,看起来像这样:
在键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级。你知道吗
我怎样才能提高这个水平呢?你知道吗
如有任何提示,我们将不胜感激。你知道吗
为了正确地获取递归,可以使用以下简单模板:
在您的情况下,您可以尝试以下操作:
不过,您应该根据自己的需要调整此代码,因为我还没有亲自测试过它。你知道吗
你有一些不必要的裁员。如果我理解正确,您需要将句柄与递归分别添加到列表中,因为您希望在父级中测试
branch
。你知道吗您不需要测试
header['children']
的长度,如果它是零,那么循环就什么也不做了。你知道吗相关问题 更多 >
编程相关推荐