You need to enable JavaScript to run this app. Python如何从字典列表聚合NR=0的Cnt值并提取Top3结果
优惠活动
大模型
产品
解决方案
定价
更多

Python如何从字典列表聚合NR=0的Cnt值并提取Top3结果

现有代码问题梳理
  • 分组键函数定义为key_func,后续调用时误写为y_func,触发NameError
  • 未先筛选NR == "0"的条目,直接对全量数据分组,混入非目标数据
  • 错误对列表resp直接取['NR']属性,触发类型错误,未对groupby返回的分组迭代器做数值累加
  • 用内置类型list作为变量名,覆盖原生列表方法
  • 原始数据中Cnt为字符串类型,未转数值无法做累加计算
  • 预期输出样例不符合Python字典规范:同一Code仅对应1个累计值,不能出现重复键
正确实现方案

方案1:字典直接累加(无需额外依赖,逻辑直观)

from collections import defaultdict

def se_conc(response):
    cnt_dict = defaultdict(int)
    # 筛选目标条目并累加Cnt
    for item in response:
        if item["NR"] == "0":
            cnt_dict[item["Code"]] += int(item["Cnt"])
    # 按累计值降序排序,取前3位
    sorted_top3 = sorted(cnt_dict.items(), key=lambda x: x[1], reverse=True)[:3]
    return dict(sorted_top3)

# 测试运行
resp = [{"NR": "0","Code": "4_RESOURCE","Cnt": "11"}, {"NR": "10","Code": "10_humans","Cnt": "1"},{"NR": "1000","Code": "4_RESOURCE","Cnt": "120"}, {"NR": "0","Code": "10_humans","Cnt": "12"}, {"NR": "0","Code": "4_RESOURCE","Cnt": "15"}, {"NR": "0","Code": "50_animals","Cnt": "20"}]
print(se_conc(resp))

运行输出:{'4_RESOURCE': 26, '50_animals': 20, '10_humans': 12}

方案2:适配原有groupby思路的实现

from itertools import groupby

def se_conc(response):
    # 先筛选NR为0的条目,再按Code排序(groupby要求同组数据相邻)
    filtered = [item for item in response if item["NR"] == "0"]
    filtered.sort(key=lambda x: x["Code"])
    cnt_dict = {}
    # 分组累加Cnt
    for code, group in groupby(filtered, key=lambda x: x["Code"]):
        cnt_dict[code] = sum(int(item["Cnt"]) for item in group)
    # 排序取Top3
    sorted_top3 = sorted(cnt_dict.items(), key=lambda x: x[1], reverse=True)[:3]
    return dict(sorted_top3)

如果需要保留累计明细(如标注26(15+11)),可调整累加逻辑存储明细,但需注意Python字典键唯一,无法实现样例中重复4_RESOURCE键的结构,可调整为嵌套字典格式存储明细。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 00:06:03