Python字典的深度
我有以下字典:Python字典的深度,python,dictionary,Python,Dictionary,我有以下字典: {} 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:
{} 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。
最后,最后一个深度=3是否正确,以及如何获得它。谢谢
Elias测试用例:
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
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
0
1
2
2
3
测试用例:
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
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
0
1
2
2
3
第二本词典的深度是多少?这只是一本字典。同样,最后一个是1。只要数一数开头和结尾的花括号对的数目,第二本字典的深度是2?这只是一本字典。同样,最后一个是1。只要数一数开始和结束的花括号的数量,你就棒极了。非常感谢你,我很乐意帮忙。你真棒。非常感谢,我很乐意帮忙。