【问题标题】:How to reduce an array of objects in Python?如何减少 Python 中的对象数组?
【发布时间】:2023-01-20 00:23:32
【问题描述】:

对于这个模糊的问题,我深表歉意,我是 Python(JavaScript 开发人员)的新手,并试图将一个对象数组缩减为一个数组,如果它们具有匹配的 ID,则将对象组合在一起。我尝试使用 functools 中的 reduce,但是,我遇到了麻烦。

    from functools import reduce

    # Attempt
    result = reduce((lambda x, y: x + y), [
        {
            "id": '111',
            "error": "MissingError",
            "message": "Missing data",
        },
        {
            "id": '111',
            "error": "Warning",
            "message": "Missing attribute",
        },
        {
            "id": '222',
            "error": "MissingError",
            "message": "Missing data",
        }
    ])
    
    print('Result', result)

    # Expected
    expected = [
        {
            "id": '111',
            "messages": [
                {
                    "error": "MissingError",
                    "message": "Missing data",
                },
                {
                    "error": "Warning",
                    "message": "Missing attribute",
                }
            ]
        },
        {
            "id": '222',
            "error": "MissingError",
            "messages": [
                {
                    "error": "MissingError",
                    "message": "Missing data",
                }
            ]
        },
    ]

【问题讨论】:

    标签: python


    【解决方案1】:

    这不是减少操作,您是按 ID 分组,然后累积到列表中。

    from collections import defaultdict
    
    grp = defaultdict(list)
    
    for d in data:
        d = d.copy()
        grp[d.pop('id')].append(d)
    
    result = [{'id': k, 'messages': v} for k, v in grp.items()]
    

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 2019-03-26
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多