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

Python购物车字典列表更新商品数量 解决list调用update报错问题

Python购物车商品新增逻辑修复方案

错误原因分析

  • 报错1:AttributeError: 'list' object has no attribute 'update'

原因:cart_products为列表类型,update()是字典专属方法,列表不存在该方法,直接调用会触发属性错误。

  • 报错2:IndexError: list index out of range

原因:matching_product是从购物车筛选生成的临时列表,清空该列表不会修改原购物车数据,反而会导致后续访问列表元素时因列表为空触发索引错误,直接追加新商品还会造成购物车出现重复同款商品。

可正常运行的完整代码

def product_exists(product: dict, cart: list):
    added_id = product.get("prod_id")
    in_cart = [existing_prod for existing_prod in cart if existing_prod.get("prod_id") == added_id] 
    if in_cart and len(in_cart) > 0:
        return True, in_cart
    return False, None

add_product = {'prod_id': 18, 'prod_name': 'Cat', 'prod_price': 30, 'prod_quantity': 2}
cart_products = [{'prod_id': 15, 'prod_name': 'Penguin', 'prod_price': 40, 'prod_quantity': 1}, {'prod_id': 16, 'prod_name': 'Lion', 'prod_price': 20, 'prod_quantity': 2}, {'prod_id': 16, 'prod_name': 'Lion', 'prod_price': 20, 'prod_quantity': 4}, {'prod_id': 17, 'prod_name': 'Whale', 'prod_price': 20, 'prod_quantity': 1}, {'prod_id': 18, 'prod_name': 'Cat', 'prod_price': 30, 'prod_quantity': 1}]

exists, matching_product = product_exists(add_product, cart_products)

if exists: # 商品已在购物车中
    update_quantity = matching_product[0]['prod_quantity'] + add_product['prod_quantity']
    print(update_quantity)
    print(matching_product[0]['prod_name'])
    # 直接修改购物车中匹配商品的数量(字典为可变对象,修改引用直接同步到原购物车)
    matching_product[0]['prod_quantity'] = update_quantity
else:
    cart_products.append(add_product)

# 打印更新后的购物车数据
print("===== 更新后的购物车 =====")
for item in cart_products:
    print(item)

运行效果说明

原购物车中ID为18的Cat商品原有数量为1,新增2后会自动合并为3,其余商品数据保持不变,不会出现重复商品。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:45:02