【问题标题】:Pythonic way to iterate through json filePythonic 方式来遍历 json 文件
【发布时间】:2022-01-08 23:56:58
【问题描述】:

我有一个类似结构的 .json 文件:

{
  "cars": [
    {
    "FIAT": [
      {"model_id": 153},
      {"model_id": 194}
    ]
    },
    {
    "AUDI": [
      {"model_id": 261}
    ]
    },
    {
    "BMW": [
      {"model_id": 264}
    ]
    }
  ]
}

我的最终目标是检索以下内容:

      {"model_id": 153},
      {"model_id": 194},
      {"model_id": 261},
      {"model_id": 264}

目前我得到这个结果的代码是这样的:

    for cars in dir['cars']:
        for brand in cars:
            for model in cars[brand]:
                print(model)

我的问题是我们是否有更好的方法来访问这些详细信息?我知道itertools.product是用来代替嵌套for循环的,但是这种场景可以应用吗?

【问题讨论】:

  • 关于哪些标准的更好方法?
  • @DaniMesejo 更 Python 的方式,或者更好的性能可能

标签: python json for-loop itertools


【解决方案1】:

您可以使用jq 来处理 json 并提取您想要的内容。这是您的数据示例https://jqplay.org/s/mIaelGNpXO

【讨论】:

    【解决方案2】:

    product 在这里没有用,因为您没有两个独立的列表来计算产品。 (您实际上也不想要任何产品)。但是,您可以使用具有多个迭代器的列表推导

    [x for c in d['cars'] for v in c.values() for x in v]
    

    其中一个可以替换为itertools.chain 对生成器表达式进行操作:

    list(chain.from_iterable(v for c in d['cars'] for v in c.values()))
    

    您可以再次申请chain.from_iterable

    list(chain.from_iterable(chain.from_iterable(c.values() for c in d['cars'])))
    

    尽管可读性可能开始受到影响。


    消除所有显式迭代的最终版本

    from itertools import chain
    from functools import methodcaller
    
    list(chain.from_iterable(
           chain.from_iterable(
            map(methodcaller('values'), d['cars'])))
    

    仅适用于函数式编程和高阶函数的最极端拥护者:)

    【讨论】:

      【解决方案3】:

      我认为这正是ijson 试图解决的问题,从 json 文件中加载部分信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-17
        • 1970-01-01
        • 2016-01-21
        • 1970-01-01
        • 2016-02-04
        • 1970-01-01
        • 2011-11-29
        相关资源
        最近更新 更多