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

Python嵌套购物列表与购物车列表匹配求和函数无输出问题排查

修复Python购物车小计计算函数的问题

需求说明

从嵌套列表shopping_list中匹配cart列表内的商品,提取对应价格并求和(示例:8.99 + 10.99 + 8.99 = 28.97)。

给定数据:

shopping_list = [['1', 'shirt', '8.99'], ['2', 'pants', '10.99'], ['3', 'socks', '5.99'], ['4', 'hat', '9.99'], ['5', 'shoes', '14.99']]
cart = ['shirt', 'pants', 'shirt']

原函数问题分析

你编写的subtotal函数运行无输出,核心问题如下:

  • 条件判断完全错误:shopping_list[i][0]是字符串类型的商品编号(如'1'),而i是从0开始的整数索引,两者永远不相等,导致if块内的所有逻辑都不会执行,自然没有输出。
  • 价格转换丢失精度:用int()转换价格字符串会丢弃小数部分,应该使用float()。
  • 打印位置不合理:print语句放在shopping_list的循环内部,即使条件满足也会多次输出,不符合需求。

修复后的函数实现

方案1:修正原逻辑问题

def subtotal(shopping_list, cart):
    total = 0.0
    # 遍历购物清单中的每个商品条目
    for item in shopping_list:
        _, item_name, price_str = item
        price = float(price_str)
        # 统计当前商品在购物车中的数量并累加总价
        total += price * cart.count(item_name)
    print('Your subtotal is ', total)
    return total

方案2:高效字典映射写法(推荐)

先将购物清单转换为商品名到价格的字典,避免重复遍历cart统计数量,提升效率:

def subtotal(shopping_list, cart):
    # 构建商品-价格映射字典
    price_dict = {item[1]: float(item[2]) for item in shopping_list}
    total = 0.0
    # 遍历购物车累加价格
    for item in cart:
        if item in price_dict:
            total += price_dict[item]
    print('Your subtotal is ', total)
    return total

测试验证

调用函数后会正确输出小计:

subtotal(shopping_list, cart)
# 输出:Your subtotal is  28.97

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 01:46:04