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

如何为在线商店订单字典添加total_cost与customer_name字段?

问题解决:给订单添加总费用和客户名称

原代码的问题

  1. 总费用计算错误:循环计算每个商品金额时,直接用=赋值,导致最后只保留了最后一个商品的金额,没有累加所有商品的总价。
  2. 未修改原订单字典:代码只打印了结果,没有把total_cost和customer_name添加到对应的订单字典中。
  3. 未处理缺失的客户数据:对于customer_id=1005的订单,原代码完全没处理,不会添加客户名称。
  4. 查找客户效率低:嵌套循环订单和客户列表,数据量大时会变慢。

正确实现代码

# 先把客户列表转成字典,用customer_id做键,快速查找
customer_map = {c['customer_id']: c['name'] for c in customers}

for order in orders:
    # 计算订单总费用:累加每个商品的数量*价格
    total_cost = sum(item['quantity'] * item['price'] for item in order['line_items'])
    # 添加总费用到订单字典
    order['total_cost'] = total_cost
    
    # 查找客户名称,找不到则设为'Unknown'
    customer_name = customer_map.get(order['customer_id'], 'Unknown')
    # 添加客户名称到订单字典
    order['customer_name'] = customer_name

验证结果

运行后,每个订单字典都会新增对应的键值对,比如:

  • 订单1会变成:
{'order_id': 1, 'customer_id': 1001, 'line_items': [...], 'total_cost': 32.5, 'customer_name': 'Alice'}
  • 订单5(customer_id=1005)会得到:
{'order_id': 5, 'customer_id': 1005, 'line_items': [...], 'total_cost': 30.0, 'customer_name': 'Unknown'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:33:37