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

Python账单打印异常:重复显示商品项问题排查求助

解决账单打印重复显示最后一项的问题

嘿,我一眼就看到问题出在哪了!你遇到的重复显示最后一项商品的问题,核心原因是你一直在复用同一个grocery_item字典对象。

每次循环你只是修改这个字典里的键值对,然后把它添加到grocery_history列表中,但列表里存储的是字典的引用(不是副本)。这就好比你把同一个本子反复放进不同的文件夹里,最后打开任何一个文件夹看到的都是你最后一次修改的内容。

解决方案:每次循环创建新字典

把grocery_item = {}放到while循环的内部,这样每次添加到列表的都是全新的字典对象,不会互相覆盖。

修正后的完整代码

grocery_history = []
stop = 'c'
while stop == 'c':
    # 每次循环新建一个空字典
    grocery_item = {}
    item_name = input("Item name:\n")
    quantity = input("Quantity purchased:\n")
    cost = input("Price per item:\n")
    grocery_item['name'] = item_name
    grocery_item['number'] = quantity
    grocery_item['price'] = float(cost)
    grocery_history.append(grocery_item)
    stop = input("Would you like to enter another item?\n Type 'c' for continue or 'q' to quit:\n")

grand_total = 0
for items in range(0, len(grocery_history)):
    item_total = int(grocery_history[items].get('number')) * float(grocery_history[items].get('price'))
    grand_total += item_total
    print(f"{grocery_history[items]['number']} {grocery_history[items]['name']} @ ${grocery_history[items]['price']} ea ${item_total:.2f}")
    item_total = 0
print(f"Grand total: ${grand_total:.2f}")

另外我还顺手把你的字符串拼接改成了f-string,这样代码更简洁易读,输出格式也和你预期的完全一致~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:05:03