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

Python如何从products字典提取价格计算cart购物车总金额

实现方案

核心思路

  • 先把products列表转换成以product_id为键的映射字典,能快速通过id查询到对应商品的全部信息,不用每次循环查找
  • 遍历购物车条目,用商品id从映射字典取单价,乘以购买数量累加得到总金额

注意:原代码中product_id=777的芝士汉堡在products定义里缺失了price字段,以下实现先补全该字段值为4.0保证逻辑可运行,如果需要动态根据食材成本计算售价,可以额外加食材成本核算逻辑。

可运行代码

ingredient=[{'product_id': 234, 'product_name':'meat', 'price':3.5}, {'product_id':324, 'product_name':'pickles', 'price':1.0}, {'product_id':146, 'product_name':'roll', 'price':3.0}, {'product_id':289, 'product_name':'chees', 'price':2.5}]
# 补全了cheesburger的price字段
products=[{'product_id':634, 'product_name':'hamburger', 'price':3.5, 'ingredients':[{'product_id':234, 'quantity':1}, {'product_id':324, 'quantity':1}, {'product_id':146, 'quantity':1}]}, {'product_id':777,'product_name':'cheesburger','price':4.0, 'ingredients':[{'product_id':234, 'quantity':1}, {'product_id':324, 'quantity':1}, {'product_id':146, 'quantity':1}, {'product_id':289, 'quantity':1}]}]
cart=[{'product_id':634, 'quantity':2}, {'product_id':777, 'quantity':4}]

# 构造product_id到商品信息的映射字典
product_map = {p['product_id']: p for p in products}

summary_price = 0
for item in cart:
    product = product_map[item['product_id']]
    summary_price += product['price'] * item['quantity']

print('Summary price is:', summary_price)

运行结果

Summary price is: 23.0

如果需要动态根据食材计算商品售价不需要在products里预填price,可以用以下逻辑:

# 先构造食材id到价格的映射
ingredient_map = {i['product_id']: i['price'] for i in ingredient}

# 动态计算每个商品的售价
product_map = {}
for p in products:
    product_cost = 0
    for ing in p['ingredients']:
        product_cost += ingredient_map[ing['product_id']] * ing['quantity']
    # 可以在这里加利润比例,比如乘以1.3就是30%利润,这里直接按成本算
    product_map[p['product_id']] = {'price': product_cost}

# 后续计算购物车总金额逻辑和之前一致
summary_price = 0
for item in cart:
    product = product_map[item['product_id']]
    summary_price += product['price'] * item['quantity']

print('按食材成本计算的总金额为:', summary_price)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:45:02