Python dict中的递归
我有一个嵌套的Python dict中的递归,python,dictionary,recursion,Python,Dictionary,Recursion,我有一个嵌套的dict,它看起来像这样: 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']: retur
dict
,它看起来像这样:
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
键子项中有多个嵌套。只要存在键子项
,我就想捕获键分支
。因为有多个子项
,所以我希望为每个子项执行此操作。当然,每个孩子还可以有更多的孩子
。这种嵌套可以达到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级
我如何改进此功能以获得所有级别
任何提示都将不胜感激。您有一些不必要的冗余。如果我理解正确,您需要将句柄与递归分开添加到列表中,因为您希望在父级中测试分支
def GatherConcepts(header):
if 'children' in header and 'branch' in header:
for child in header['children']:
concepts.append(child['handle'])
GatherConcepts(child)
您不需要测试头['children']
的长度——如果它为零,那么循环将什么也不做。为了正确地获得递归,您可以使用以下简单模板:
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
不过,您应该根据自己的需要调整此代码,因为我自己还没有测试过它。您可以展示一个输入示例(提供的示例可以)以及您期望从中获得的输出吗?看起来顶级dict有子项,但没有分支(除非我错误地读取了该输出)…还有,FWIW,key in some dict.keys()
比key in some dict.keys()
效率低(在python2.x上显著)。如果header.keys()中有“children”,则第二个是不必要的。您已经在函数顶部测试过了,它不会改变。请注意,还有改进工作代码的方法。我不想要分支的句柄,我想要子级的句柄。我同意第二个if声明是不必要的。我加入它只是为了尝试更多的东西。这个代码在大多数情况下都很好用,但它给了我分支的句柄
,而我想要孩子的句柄
。我在20分钟前把它拿出来,现在它给了孩子的句柄。但前提是孩子也有分支。我误解了吗?啊,对不起,看起来我用错了代码。你的代码运行得很好,非常感谢:)。现在仔细看一下这篇文章,我认为分支的句柄可能也没有必要了。我只在每个子项中的句柄
字段后面。我只想要子项中存在的所有句柄的最终列表
。