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

如何简化Python订单数据统计脚本:计算总销量与总营收

精简实现订单商品总数量与总营收统计

最优精简实现

利用Python的生成器表达式可直接完成统计,无需创建多个中间列表,代码更紧凑且内存效率更高:

# 统计总售出数量
total_count = sum(item.get("count", 0) for order in sales_data for item in order.get("items", []))

# 统计总营收(兼容prices列表多元素的情况)
total_revenue = sum(price.get("total", 0) for order in sales_data 
                    for item in order.get("items", []) 
                    for price in item.get("prices", []))

print(total_count)  # 输出:18
print(total_revenue)  # 输出:1204.0

针对示例数据的进一步简化

如果业务场景中每个商品的prices列表固定只有一个元素(如示例所示),可进一步简化总营收计算:

total_revenue = sum(item.get("prices", [{}])[0].get("total", 0) 
                    for order in sales_data 
                    for item in order.get("items", []))

与原有代码的对比

原有代码通过创建多个中间列表(counts、prices、total_earned)存储临时数据再求和,既增加了内存占用,代码结构也较繁琐。生成器表达式采用惰性求值,遍历过程中直接累加计算,无需额外存储中间结果,既精简了代码,又提升了性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:07:52