在Python中获取json文件的深度

发布于 2025-01-17 10:18:07 字数 783 浏览 0 评论 0原文

我是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文