【发布时间】:2021-01-07 20:44:45
【问题描述】:
我有一个 JSON 对象,我想编写一个 Python 程序,将其作为输入并计算其最大深度。
代码,
f = open(r"c:\python\8_DEPTH\JSON_Kino.JSON", "r")
x = f.read()
def depth(x):
if type(x) is dict and x:
return 1 + max(depth(x[a]) for a in x)
if type(x) is list and x:
return 1 + max(depth(a) for a in x)
return 0
print(depth(x))
我的问题是当我运行程序时它计数为 0。有什么想法吗???
【问题讨论】:
-
x总是一个字符串,这就是为什么你的函数总是返回 0 -
欢迎来到 SO!显示您的 JSON 是个好主意。正如 Moinuddin 所说,您尚未将 JSON 字符串解析为 dict 或列表,因此该函数仅返回 0,因为两个分支都不为真。您的意思是先使用
json.loads(x)吗? -
您可以将答案标记为解决方案,但请不要在问题中输入(已解决)。见What should I do when someone answers my question?
标签: python arrays json nested-lists