【问题标题】:aggregation of a dictionary list字典列表的聚合
【发布时间】:2019-07-24 01:03:26
【问题描述】:

我正在尝试对我正在开发的 django 应用程序中的这些数据进行排序和汇总。问题是我迷失了遍历列表和存储数据的最佳方式。

这是我所拥有的示例:

from score.models import LocData

q = [
        {'ref': '002', 'loc': 'seattle', 'total': '200'}, 
        {'ref': '002', 'loc': 'seattle', 'total': '100'}, 
        {'ref': '123', 'loc': 'dallas', 'total': '100'}, 
        {'ref': '452', 'loc': 'cleveland', 'total': '600'}, 
        {'ref': '123', 'loc': 'dallas', 'total': '200'}, 
        {'ref': '002', 'loc': 'seattle', 'total': '300'}
        ]

我想最终得到的是下面的列表,它由 ref 字段聚合并使用 loc 维护该字段,但添加了 total 字段。这是所需的输出。

q = [
        {'ref': '002', 'loc': 'seattle', 'total': '600'}, 
        {'ref': '123', 'loc': 'dallas', 'total': '300'}, 
        {'ref': '452', 'loc': 'cleveland', 'total': '600'}, 
        ]

有人能告诉我我有哪些工具可以做到这一点吗?提前致谢!

【问题讨论】:

  • 熊猫可以轻松做到这一点。
  • 看到这个答案,你可以使用来自 itertools 的 groupby stackoverflow.com/a/18180813/10548514
  • @Barmar 我是狐狸,可能是因为熊猫有对生的拇指?

标签: python


【解决方案1】:

您可以使用collections.Counter 聚合:

from collections import Counter
from pprint import pprint

q = [
    {"ref": "002", "loc": "seattle", "total": "200"},
    {"ref": "002", "loc": "seattle", "total": "100"},
    {"ref": "123", "loc": "dallas", "total": "100"},
    {"ref": "452", "loc": "cleveland", "total": "600"},
    {"ref": "123", "loc": "dallas", "total": "200"},
    {"ref": "002", "loc": "seattle", "total": "300"},
]

counts = Counter()
for x in q:
    ref, loc, total = x["ref"], x["loc"], x["total"]
    counts[ref, loc] += int(total)

pprint(
    [
        {"ref": ref, "loc": loc, "total": str(total)}
        for (ref, loc), total in counts.items()
    ]
)
#[{'loc': 'seattle', 'ref': '002', 'total': '600'},
# {'loc': 'dallas', 'ref': '123', 'total': '300'},
# {'loc': 'cleveland', 'ref': '452', 'total': '600'}]

【讨论】:

    【解决方案2】:

    您可以先构造一个中间字典,然后根据所需的输出对其进行转换:

    from collections import defaultdict
    
    q = [
            {'ref': '002', 'loc': 'seattle', 'total': '200'}, 
            {'ref': '002', 'loc': 'seattle', 'total': '100'}, 
            {'ref': '123', 'loc': 'dallas', 'total': '100'}, 
            {'ref': '452', 'loc': 'cleveland', 'total': '600'}, 
            {'ref': '123', 'loc': 'dallas', 'total': '200'}, 
            {'ref': '002', 'loc': 'seattle', 'total': '300'}
        ]
    
    temp_dict = defaultdict(int)
    
    for entry in q:
        temp_dict[(entry['ref'], entry['loc'])] += int(entry['total'])
    
    result = [{'ref': k[0], 'loc': k[1], 'total': str(v)} for k, v in temp_dict.items()]
    print(result)
    
    # [{'ref': '002', 'loc': 'seattle', 'total': '600'},
    #  {'ref': '123', 'loc': 'dallas', 'total': '300'},
    #  {'ref': '452', 'loc': 'cleveland', 'total': '600'}]
    

    【讨论】:

    • 这帮助我理解了我的问题,感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    相关资源
    最近更新 更多