如何计算嵌套字典列表的数值总和并生成汇总统计字典
嵌套字典列表的汇总统计实现方案
实现代码
def calculate_grand_summary(dict_list): # 初始化汇总字典,结构与单个统计字典匹配 grand_summary = { "totals": {"total": 0, "correct": 0, "false": 0}, "label": {} } # 遍历所有统计字典,累加核心数值 for d in dict_list: # 累加全局统计项 grand_summary["totals"]["total"] += d["totals"]["total"] grand_summary["totals"]["correct"] += d["totals"]["correct"] grand_summary["totals"]["false"] += d["totals"]["false"] # 累加各标签的统计项 for label_name, stats in d["label"].items(): if label_name not in grand_summary["label"]: grand_summary["label"][label_name] = {"total": 0, "correct": 0, "false": 0} grand_summary["label"][label_name]["total"] += stats["total"] grand_summary["label"][label_name]["correct"] += stats["correct"] grand_summary["label"][label_name]["false"] += stats["false"] # 计算全局统计的正确率和错误率 total_count = grand_summary["totals"]["total"] if total_count > 0: grand_summary["totals"]["correct_Percent"] = (grand_summary["totals"]["correct"] / total_count) * 100 grand_summary["totals"]["wrong_percent"] = (grand_summary["totals"]["false"] / total_count) * 100 else: # 避免除以0的异常情况 grand_summary["totals"]["correct_Percent"] = 0.0 grand_summary["totals"]["wrong_percent"] = 0.0 # 计算各标签的正确率和错误率 for label_name, stats in grand_summary["label"].items(): label_count = stats["total"] if label_count > 0: stats["correct_Percent"] = (stats["correct"] / label_count) * 100 stats["wrong_percent"] = (stats["false"] / label_count) * 100 else: stats["correct_Percent"] = 0.0 stats["wrong_percent"] = 0.0 return grand_summary # 示例使用 if __name__ == "__main__": # 模拟包含10个统计字典的列表 list_of_10_dictionaries = [my_single_dictionary for _ in range(10)] result = calculate_grand_summary(list_of_10_dictionaries) import pprint pprint.pprint(result)
核心逻辑说明
- 结构初始化:提前搭建好与单个统计字典一致的汇总结构,避免后续键不存在的报错。
- 数值累加:分全局统计(
totals)和标签统计(label)两部分遍历累加,遇到新标签时自动初始化对应的统计项。 - 百分比计算:基于累加后的总数量重新计算正确率和错误率,加入除以0的判断逻辑,保证代码健壮性。
- 格式输出:使用
pprint模块可以让最终结果的格式更清晰,完全匹配你需要的输出结构。
内容的提问来源于stack exchange,提问作者Faisal
相关产品推荐
相关产品推荐

