You need to enable JavaScript to run this app. Python如何按id、note多键分组字典列表并统计出现次数
优惠活动
大模型
产品
解决方案
定价
更多

Python如何按id、note多键分组字典列表并统计出现次数

Python 按多字段分组统计字典列表次数实现方案

实现逻辑

  • 把id和note两个字段拼成元组作为唯一分组键
  • 遍历字典列表时,累计同分组的出现次数,同分组下的name默认保留最后一次遍历到的值
  • 遍历完成后直接提取统计结果即可

完整可运行代码

# 原始字典列表
my_list = [
    {"name": "alin", "id": 2, "note": -10},
    {"name": "alin", "id": 2, "note": -10},
    {"name": "alin", "id": 2, "note": -10},
    {"name": "milanie", "id": 3, "note": 11},
    {"name": "martin", "id": 3, "note": 11}
]

group_res = {}
for item in my_list:
    # 生成多字段分组键
    key = (item["id"], item["note"])
    if key not in group_res:
        # 首次遇到该分组初始化数据
        group_res[key] = item.copy()
        group_res[key]["occ"] = 1
    else:
        # 已有分组累计次数,更新name为当前条目值
        group_res[key]["occ"] += 1
        group_res[key]["name"] = item["name"]

# 提取所有分组的统计结果列表
final_list = list(group_res.values())
# 单独获取id=3、note=11的分组结果
target_item = next(i for i in final_list if i["id"] == 3 and i["note"] == 11)
print(target_item)

输出结果

{'name': 'martin', 'id': 3, 'note': 11, 'occ': 2}

补充说明

如果你需要基于你已经新增了occ字段的列表统计,先修复你给出的那段代码的语法错误(occ:3后多了一个多余的右大括号),统计时把occ +=1改成occ += item.get("occ", 1)即可适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 00:54:06