如何在用户添加商品时自动为购物清单字典分配新数字键?
问题解决:购物清单自动生成递增数字键
需求与问题
- 需求:用户添加商品时,
shopping_list字典自动分配**递增数字(1、2、3…)**作为键,键对应的值为商品名称和价格的列表 - 问题:现有代码仅能让字典保留一个键,无法实现多商品添加
原代码
# 便利店商品库存:包含编号、名称、价格(分)、库存 items = { 0:['black tea',500,20], 1:['red tea',500,1], 2:['milk tea',500,0]} shopping_list = {} query = input("Enter the code number of the item you want to get: ") query = int(query) for i in items: if query == i: item = i print(items[item][0], "will cost you", "{:.2f}".format(items[item][1]/100),"dollars") # 临时购物清单需存储原商品列表中的商品编号、名称和价格 n=0 buy_more = input("Do you wish to choose some more items? (Y or N) ") while buy_more.isdigit() and buy_more not in "Yy" and buy_more not in "Nn": print("Please enter (Y or N) only. ") buy_more = input("Do you wish to choose some more items? (Y or N) ") # 循环让用户添加更多商品 while buy_more in "Yy": shopping_list[n] = [items[item][0],items[item][1]] print("Nice! Please choose one more item.") buy_more = input("Do you wish to choose some more items? (Y or N) ") # 进入交易流程 if buy_more in "Nn": print("Continue to transaction process. ") break shopping_list[n] = [items[item][0],items[item][1]] print(shopping_list)
问题原因
- 变量
n初始化后从未递增,每次添加商品都会覆盖键0,导致字典仅保留最后一次添加的商品 - 循环逻辑混乱:外层
while条件错误,用户选择添加更多商品时未重新输入新商品编号,始终添加同一商品
修正后的代码
# 便利店商品库存:包含编号、名称、价格(分)、库存 items = {0: ['black tea', 500, 20], 1: ['red tea', 500, 1], 2: ['milk tea', 500, 0]} shopping_list = {} def add_to_shopping_list(): """添加商品到购物清单,自动生成递增键""" # 计算下一个递增键:空字典从1开始,否则取当前最大键+1 max_key = max(shopping_list.keys()) if shopping_list else 0 new_key = max_key + 1 # 校验商品编号输入合法性 while True: try: query = int(input("请输入想要购买的商品编号:")) if query in items: item_info = items[query] shopping_list[new_key] = [item_info[0], item_info[1]/100] print(f"{item_info[0]} 价格为 {item_info[1]/100:.2f} 美元,已加入购物清单") break else: print("该商品编号不存在,请重新输入") except ValueError: print("请输入有效的数字编号") # 首次添加商品 add_to_shopping_list() # 循环询问是否继续添加 while True: buy_more = input("是否还要选购其他商品?(Y/N) ").strip().upper() if buy_more == 'Y': add_to_shopping_list() elif buy_more == 'N': print("进入交易流程") break else: print("请仅输入Y或N") print("购物清单:", shopping_list)
修正说明
- 用
max(shopping_list.keys())自动计算下一个递增键,避免固定变量覆盖问题 - 封装添加逻辑为函数,代码更清晰
- 完善输入校验:处理非数字输入、不存在的商品编号
- 重构循环逻辑,每次选择添加时重新获取新商品编号,支持多商品添加
内容的提问来源于stack exchange,提问作者Chin Fung Chan
相关产品推荐
相关产品推荐

