You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何更简便地对嵌套列表中同类别数据的totalspent求和?

按class/plan/type分组求和的简便实现方案

当然有更简便的实现方式!针对你这个按class/plan/type分组求和的需求,我给你整理了几种Python里常用的方案,从标准库到数据分析工具都有,你可以根据场景选择:

方案一:使用collections.defaultdict(标准库,推荐小数据集)

这是最基础且直观的实现方式,不需要额外安装依赖,适合处理中小型数据集:

from collections import defaultdict

# 初始化默认字典,用(class, plan, type)元组作为唯一键,值用于累加金额
sum_counter = defaultdict(int)

for c in classes:
    # 生成分组键
    group_key = (c.get('class'), c.get('plan'), c.get('type'))
    # 安全提取totalspent,避免空值报错
    spent = c.get('money', [{}])[0].get('totalspent', 0)
    sum_counter[group_key] += spent

# 打印最终结果
for key, total in sum_counter.items():
    print(*key, total)

方案二:使用itertools.groupby(标准库,需先排序)

如果想用另一种标准库方法,可以用groupby,但要注意必须先对列表按分组键排序,因为groupby只会把连续的相同元素归为一组:

from itertools import groupby

# 先按分组键排序,确保相同组的元素连续
sorted_classes = sorted(classes, key=lambda x: (x.get('class'), x.get('plan'), x.get('type')))

# 分组并累加求和
for group_key, items in groupby(sorted_classes, key=lambda x: (x.get('class'), x.get('plan'), x.get('type'))):
    total_spent = 0
    for item in items:
        total_spent += item.get('money', [{}])[0].get('totalspent', 0)
    print(*group_key, total_spent)

方案三:使用pandas(适合大数据/数据分析场景)

如果你的数据量较大,或者后续还有更多数据分析需求,pandas的分组功能会更高效简洁:

import pandas as pd

# 将原始列表转换为DataFrame
df = pd.DataFrame(classes)
# 提取money字段中的totalspent,处理空值情况
df['totalspent'] = df['money'].apply(lambda x: x[0].get('totalspent', 0) if x else 0)

# 一行完成分组求和
result_df = df.groupby(['class', 'plan', 'type'])['totalspent'].sum().reset_index()

# 按要求格式输出结果
for _, row in result_df.iterrows():
    print(row['class'], row['plan'], row['type'], row['totalspent'])

总结

  • 小数据集且依赖少:选defaultdict,简单直接
  • 偏好标准库且能接受排序:选groupby
  • 大数据或需要后续分析:选pandas,效率更高且功能更丰富

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:30:19