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

Python订单加购函数传入空集合订单返回None该如何解决

问题根源
  • 你所有的逻辑代码都包裹在for item in order循环内,当传入的order是空集合时,这个循环不会执行,内部的return语句永远不会触发,函数执行完没有显式返回值,默认返回None。
  • 额外还有多处逻辑缺陷:外层无意义的for item in name, quantity, order循环、商品匹配逻辑混乱、循环提前返回导致多商品订单场景无法正常运行、KeyError触发条件错误。
修复后的完整代码
CATALOGUE = {("table", 9999, 20), ("chair", 2999, 5), ("lamp", 1999, 10)}      

def add_item_to_order(name, quantity, order):
    # 先把商品目录转成字典方便查询
    cat_map = {item[0]: {"price": item[1], "weight": item[2]} for item in CATALOGUE}
    # 先判断商品是否在目录中,不在直接抛错
    if name not in cat_map:
        raise KeyError(f"商品{name}不在目录中")
    # 生成新的订单集合,避免修改原传入的order
    new_order = set()
    existed = False
    for item in order:
        if item[0] == name:
            # 找到同名商品,更新数量
            new_item = (name, item[1] + quantity, cat_map[name]["price"], cat_map[name]["weight"])
            new_order.add(new_item)
            existed = True
        else:
            new_order.add(item)
    # 没有找到同名商品,新增到订单
    if not existed:
        new_order.add((name, quantity, cat_map[name]["price"], cat_map[name]["weight"]))
    return new_order
功能验证
  • 空订单新增商品:add_item_to_order("table", 1, set()) 输出 {('table', 1, 9999, 20)},符合要求
  • 已有商品追加数量:add_item_to_order("table", 2, {('table', 1, 9999, 20)}) 输出 {('table', 3, 9999, 20)}
  • 非空订单新增不同名商品:add_item_to_order("chair", 1, {('table', 1, 9999, 20)}) 输出 {('table', 1, 9999, 20), ('chair', 1, 2999, 5)}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:06:01