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

Python购物清单程序:如何实现商品与对应价格正确匹配显示?

问题原因与修改方案

问题出在查看购物车的代码部分:你当前的循环直接调用了item_price变量,这个变量存的是最后一次添加商品时输入的价格,所以所有商品都会显示同一个价格,导致匹配错误。

方法一:基于现有双列表修改

把查看购物车的代码改成以下两种方式之一,通过索引或zip方法对应两个列表里的商品和价格:

方式1:通过索引遍历

elif menu_selection == '2':
    for i in range(len(item_list)):
        print(f'{i+1}. {item_list[i]} - {item_price_list[i]}')

方式2:用zip同时遍历两个列表

elif menu_selection == '2':
    for idx, (item, price) in enumerate(zip(item_list, item_price_list), start=1):
        print(f'{idx}. {item} - {price}')

方法二:改用更合理的数据结构(推荐)

用字典列表存储商品和价格,让每个商品与对应价格绑定在一起,从根源避免匹配错误。修改后的完整代码如下:

print('\nWelcome to the Shopping List App!\n')

cart = []  # 每个元素是{"item": 商品名, "price": 价格}

while True:
    menu_selection = input(
    '''Please select one of the following:

    [1]: Add item
    [2]: View cart
    [3]: Remove item
    [4]: Compute total
    [5]: Quit

    Enter an action: ''')

    if menu_selection == '1':
        item = input('Add item: ').capitalize()
        item_price = input(f'What is the price of {item}? $')
        cart.append({"item": item, "price": item_price})
        print(f'\n{item} has been added to your cart.\n')
        continue
    elif menu_selection == '2':
        for idx, entry in enumerate(cart, start=1):
            print(f'{idx}. {entry["item"]} - {entry["price"]}')

修改后,商品与价格就能正确匹配,比如Bacon会显示12,Cheese显示10。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:50:42