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

Python中如何计算两个店铺列表内所有商品价格的总和?

计算两个商品列表的价格总和

首先先修正你提供的列表里的语法错误(存在符号拼写错误),修正后的数据如下:

shop1 = [{'status':'1','price':'1200'},{'status':'1','price':'13000'}]
shop2 = [{'status':'2','price':'3000'},{'status':'2','price':'4000'}]

接下来可以通过以下步骤计算总和:

  1. 合并两个列表,得到所有商品的集合
  2. 遍历每个商品字典,提取price字段并转换为整数(因为原始数据里的价格是字符串类型)
  3. 累加所有价格数值

实现代码如下:

# 修正后的列表
shop1 = [{'status':'1','price':'1200'},{'status':'1','price':'13000'}]
shop2 = [{'status':'2','price':'3000'},{'status':'2','price':'4000'}]

# 合并列表并计算总和
total = sum(int(item['price']) for item in shop1 + shop2)
print(total)  # 输出结果:21200

如果原始数据里的价格已经是整数类型(比如修正后shop2的price是整数),可以去掉int()转换,直接求和:

shop1 = [{'status':'1','price':1200},{'status':'1','price':13000}]
shop2 = [{'status':'2','price':3000},{'status':'2','price':4000}]

total = sum(item['price'] for item in shop1 + shop2)
print(total)  # 同样输出21200

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:55:19