【发布时间】:2021-04-23 15:27:52
【问题描述】:
我想知道包含字典列表的字典的深度,我写了一个简单的代码,但问题是它在每一步都会增加深度计数器。
这是我作为示例的输入:
respons = {
"root":{
"Flow":[{
"Name":"BSB1",
"Output":[{
"Name":"BSB2",
"Output":[{
"Name":"BSB5",
"Output":[{
"Name":"BSB6",
"Output":[{
"Name":"BSB8",
"Output":[]
}]
},
{
"Name":"BSB7",
"Output":[]
}]
}]
},
{
"Name":"BSB3",
"Output":[{
"Name":"BSB4",
"Output":[]
}]
}]
}]
}
}
def calculate_depth(flow,depth):
depth+=1
md = []
if flow['Output']:
for o in flow['Output']:
print(o['BusinessUnit'])
md.append(calculate_depth(o,depth))
print(max(md))
print(md)
return max(md)
else:
return depth
print(calculate_depth(respons['root']['Flow'][0],0))
通常我希望这个字典的最长分支的深度不要遍历所有分支并在每一步递增
编辑
这个结构的期望结果是:5 为什么 ? 它是最长的分支 BSB1 => BSB2 => BSB5 => BSB6 => BSB8
【问题讨论】:
-
您能补充一下想要的结果吗?也就是说,问题中字典的预期深度是多少(最好解释原因)。此外,您能否编辑您的问题以包含您的代码返回的内容(以及为什么这不是预期的结果)?
-
@NikolaosChatzis 我更新了问题谢谢你在高级
标签: python json python-3.x algorithm dictionary