在Python中获取json文件的深度
我是Python的新手,目前正在使用JSON文件。我的任务是获取数据集的嵌套深度。
data= [{'medprice': '1144942',
'medprice_ia': '1664657',
'percentchngprice': '1.01',
'percentchngpriceia': '0.64',
'source': 'Zillow',
'year': '2003',
'zipcode': '94123'}]
json属性带有另一个对象为值(或另一个对象作为列表值的成员,将文件的深度提高了1
我尝试了一些想法,但这个任务似乎在此任务上做得最好,但我相信我的嵌套深度错误是因为上面的代码应返回1作为嵌套深度,而不是2。
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
我更改的唯一一件事就是将返回值降低到仅值:这样的方法
if type(x) is list and x:
for a in x:
value= max(str(depth(a)))
return value
是有更好的方法来弄清楚这一点。还是我想念什么?
I am pretty new to Python and I am currently working with json files. My task is to get the nesting depth of a data set.
data= [{'medprice': '1144942',
'medprice_ia': '1664657',
'percentchngprice': '1.01',
'percentchngpriceia': '0.64',
'source': 'Zillow',
'year': '2003',
'zipcode': '94123'}]
JSON attribute with another object as value (or another object as member of a list value increases the depth of the file by 1
I tried some ideas and this one seems to work the best regarding this task but I believe that I am getting the wrong nesting depth because the code above should return 1 as a nesting depth and not 2.
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
The only thing I changed is reducing the return value to only the value: something like this
if type(x) is list and x:
for a in x:
value= max(str(depth(a)))
return value
Is there a better way to figure this out? Or am I missing something? Cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论