【问题标题】:Depth of a Python dictionary [duplicate]Python字典的深度[重复]
【发布时间】:2021-02-25 16:33:08
【问题描述】:

我有以下词典:

{} depth: 0  
{"x":5} depth: 1  
{"x":5,"y":[1,2,3]} depth: 2  
{"x":5,"y":{"a":2,"b":67}} depth: 2  
{ "x" : 5,"y" : [ [ 1 , 2 ] , [ 3 , 4 ] ]} depth: 3 

我在互联网上进行了搜索,找到了几种方法来获得上述内容的深度,但没有人为最后一个返回 3。 最后,最后一个的 Depth = 3 是否正确,以及我如何得到它。
谢谢
埃利亚斯

【问题讨论】:

  • 第二个字典的深度2怎么样?它只是一本字典。同理,最后一个是1。只计算开闭花括号的对数

标签: python dictionary


【解决方案1】:

测试用例:

testcases = [
    {}, # 0
    {"x":5}, # 1
    {"x":5,"y":[1,2,3]}, # 2
    {"x":5,"y":{"a":2,"b":67}}, # 2
    { "x" : 5,"y" : [ [ 1 , 2 ] , [ 3 , 4 ] ]} # 3
]

这是一个快速的解决方案:

level = 1
def calculate_depth(collection):
    global level
    if len(collection) == 0:
        return 0
    else:
        if isinstance(collection, dict):
            for item in collection.values():
                if isinstance(item, list) or isinstance(item, dict):
                    level += 1
                    calculate_depth(item)
                    break

        
        elif isinstance(collection, list):
            for item in collection:
                if isinstance(item, list) or isinstance(item, dict):
                    level += 1
                    calculate_depth(item)
                    break

    return level
    
# testing
for t in testcases:
    d = calculate_depth(t)
    print(d)
    level = 1

输出

0
1
2
2
3

我不喜欢全局变量level 所以,有没有全局变量的解决方案:

def calculate_depth(coll): 
    if isinstance(coll, dict): 
        if coll == {}:
            return 0
        else:
            return 1 + (max(map(calculate_depth, coll.values())))

    elif isinstance(coll, list):
        if coll == []:
            return 0
        else:
            return 1 + (max(map(calculate_depth, coll))) 
    return 0
  
# testing
for t in testcases:
    d = calculate_depth(t)
    print(d)

输出

0
1
2
2
3

【讨论】:

  • 你太棒了。非常感谢
  • 很高兴为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 2021-11-22
  • 2012-03-21
  • 2016-08-29
  • 1970-01-01
  • 2020-11-12
  • 2015-07-31
  • 2021-12-21
  • 2017-10-29
相关资源
最近更新 更多