You need to enable JavaScript to run this app. 如何基于指定Key值聚合列表中的字典并累加对应count字段值
优惠活动
大模型
产品
解决方案
定价
更多

如何基于指定Key值聚合列表中的字典并累加对应count字段值

实现方案

思路

我们可以将regex和age两个字段组合成可哈希的元组作为聚合键,用字典存储每个聚合键对应的累计count,最后转换为目标格式的列表即可,全程仅使用Python标准库,无第三方依赖。

代码实现

from collections import defaultdict

# 原始数据
data = [
    { "regex": ".*ccc-r.*", "age": 44, "count": 224 },
    { "regex": ".*nft-r.*", "age": 23, "count": 44 },
    { "regex": ".*ccc-r.*", "age": 44, "count": 20 },
    { "regex": ".*ccc-r.*", "age": 32, "count": 16 },
    { "regex": ".*nft-r.*", "age": 23, "count": 46 },
    { "regex": ".*zxy-r.*", "age": 16, "count": 55 }
]

# 定义聚合字典,key为(regex, age)元组,value为累计count
aggregator = defaultdict(int)
for item in data:
    key = (item["regex"], item["age"])
    aggregator[key] += item["count"]

# 转换为目标格式的列表
result = [
    {"regex": k[0], "age": k[1], "count": v}
    for k, v in aggregator.items()
]

输出结果

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

[
    {'regex': '.*ccc-r.*', 'age': 44, 'count': 244},
    {'regex': '.*nft-r.*', 'age': 23, 'count': 90},
    {'regex': '.*ccc-r.*', 'age': 32, 'count': 16},
    {'regex': '.*zxy-r.*', 'age': 16, 'count': 55}
]

无额外依赖的极简方案

如果你连collections模块都不想导入,可以用普通字典实现相同逻辑:

data = [
    { "regex": ".*ccc-r.*", "age": 44, "count": 224 },
    { "regex": ".*nft-r.*", "age": 23, "count": 44 },
    { "regex": ".*ccc-r.*", "age": 44, "count": 20 },
    { "regex": ".*ccc-r.*", "age": 32, "count": 16 },
    { "regex": ".*nft-r.*", "age": 23, "count": 46 },
    { "regex": ".*zxy-r.*", "age": 16, "count": 55 }
]

aggregator = {}
for item in data:
    key = (item["regex"], item["age"])
    if key not in aggregator:
        aggregator[key] = 0
    aggregator[key] += item["count"]

result = [
    {"regex": k[0], "age": k[1], "count": v}
    for k, v in aggregator.items()
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 08:54:04