知道字典的深度 [英] Know the depth of a dictionary
本文介绍了知道字典的深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
d = {'a':1,'b':{'c' :{}}}
最直接的方法是了解嵌套深度
解决方案
你必须递归:
$ d
如果不是isinstance(d,dict)或$ d $ d
返回级别
返回最大值(d [k],level + 1)for d)
max()
需要在每个级别审查的当前字典中选择最大的深度,每个不同深度的3个键的字典应该反映最大的深度
演示:
>> ; d = {'a':1,'b':{'c':{}}}
>>>深度(d)
3
>>>> d = {'foo':{'bar':{'baz':0},'spam':{'ham':{'monty':1},'eric':'idle'}},'john' :'cleese'}
>>>深度(d)
5
Supposing we have this dict:
d = {'a':1, 'b': {'c':{}}}
What would be the most straightforward way of knowing the nesting depth of it?
解决方案
You'll have to recurse:
def depth(d, level=1):
if not isinstance(d, dict) or not d:
return level
return max(depth(d[k], level + 1) for k in d)
max()
is needed to pick the greatest depth for the current dictionary under scrutiny at each level, a dictionary with 3 keys of each different depths should reflect the greatest depth at that level.
Demo:
>>> d = {'a':1, 'b': {'c':{}}}
>>> depth(d)
3
>>> d = {'foo': {'bar': {'baz': 0}, 'spam': {'ham': {'monty': 1}, 'eric': 'idle'}}, 'john': 'cleese'}
>>> depth(d)
5
这篇关于知道字典的深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文