You need to enable JavaScript to run this app. 如何用Python按公共id聚合字典数组:求marks总和与最大end_date
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python按公共id聚合字典数组:求marks总和与最大end_date

为什么Counter无法实现该需求

Counter的核心设计是统计可哈希元素的出现频次,完全不适配多字段自定义分组聚合的场景:

  • 直接传入字典列表会触发报错,因为字典是不可哈希类型,无法被Counter统计
  • 即便你按id拆分数据后传入Counter,它也只会输出每组的记录数,没法同时实现marks求和、非空end_date取最大值的逻辑,还会无意义地对id文本字段做累加,和预期偏差很大。

原生Python实现(无第三方依赖,适配绝大多数场景)

通过collections.defaultdict做分组容器,逐记录完成聚合计算,逻辑透明可控:

from collections import defaultdict
import datetime

# 原始输入数据
raw_data = [
    {'id':'450', 'marks':'30', 'end_date':datetime.datetime(2021, 2, 3, 0, 0, tzinfo=datetime.timezone.utc)},
    {'id':'450', 'marks':'60', 'end_date':datetime.datetime(2021, 2, 7, 0, 0, tzinfo=datetime.timezone.utc)},
    {'id':'450', 'marks':'80', 'end_date':None},
    {'id':'452', 'marks':'51', 'end_date':datetime.datetime(2021, 3, 1, 0, 0, tzinfo=datetime.timezone.utc)},
    {'id':'452', 'marks':'27', 'end_date':datetime.datetime(2021, 3, 3, 0, 0, tzinfo=datetime.timezone.utc)}
]

# 初始化分组容器:每个id分组存储[marks累计和, 最大非空end_date]
group_store = defaultdict(lambda: [0, None])

for record in raw_data:
    current_id = record['id']
    # marks累加:字符串转整数计算,最终结果转回字符串匹配输出格式
    group_store[current_id][0] += int(record['marks'])
    # end_date处理:跳过None值,更新分组内最大日期
    current_end = record['end_date']
    if current_end is not None:
        stored_max_date = group_store[current_id][1]
        if stored_max_date is None or current_end > stored_max_date:
            group_store[current_id][1] = current_end

# 整理为要求的输出格式
result = []
for gid, (total_marks, max_date) in group_store.items():
    result.append({
        'id': gid,
        'marks': str(total_marks),
        'end_date': max_date
    })

执行结果说明

上述代码运行后得到的输出和预期结果完全一致:

即便记录的end_date为None,对应的marks值也会正常计入分组总和,和示例业务逻辑匹配

  • 自动跳过end_date为None的记录,仅从有效日期中取最大值
  • marks字段按数值累加后转回字符串类型,保持和原数据格式一致
  • 全程仅按id字段分组,不会对id本身做无意义的聚合计算

大批量数据场景的简化实现

如果已经安装了pandas处理数据,可以通过内置的groupby聚合逻辑更简洁地实现相同需求:

import pandas as pd

df = pd.DataFrame(raw_data)
agg_result = df.groupby('id').agg(
    marks=('marks', lambda x: str(sum(int(score) for score in x))),
    end_date=('end_date', lambda x: x.dropna().max())
).reset_index()
result = agg_result.to_dict('records')

内容的提问来源于stack exchange,提问作者abhjt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.31 08:24:05