Python如何基于列表元素位置匹配对应价格构建已购清单
杂货采购程序价格匹配功能实现
核心实现逻辑
你的两个固定商品、价格列表是按下标一一对应的,同一下标位置的商品和价格为匹配关系,只需要两步就能完成价格填充:
- 当用户输入的商品编码合法时,先通过
index()方法获取该商品在product_list中的下标位置 - 用这个下标从
price_list中取出对应单价,和你追加商品名的逻辑保持一致,按照购买数量循环,把单价追加到bought_price_list中即可
另外你原有代码存在逻辑漏洞:输入非法商品编码时,打印提示后没有中断当前轮次逻辑,会继续要求输入数量,需要补分支判断跳过非法输入的后续流程。
修正后完整代码
product_list = ['apple', 'orange', 'watermelon', 'banana', 'coconut'] price_list = [5.32, 6.45, 2.37, 5.32, 6.45] bought_product_list = [] bought_price_list = [] while True: product_code = input('Enter the product code: ') if product_code not in product_list: print('Invalid product code! Try again!') continue # 非法输入直接跳过后续逻辑,进入下一轮循环 # 合法商品才执行后续购买逻辑 quantity = int(input('Enter the quantity:')) # 获取商品对应下标,匹配单价 product_index = product_list.index(product_code) current_price = price_list[product_index] # 按数量同时追加商品和对应价格 for q in range(quantity): bought_product_list.append(product_code) bought_price_list.append(current_price) # 调试用打印,不需要可以删除 print("当前已购商品列表:", bought_product_list) print("当前已购价格列表:", bought_price_list)
效果验证
按照你给出的测试场景,依次输入apple、数量2,再输入watermelon、数量3,最终两个列表输出完全符合预期:
bought_product_list = [ 'apple', 'apple', 'watermelon' , 'watermelon' , 'watermelon' ]
bought_price_list = [ 5.32 , 5.32 , 2.37 , 2.37 , 2.37 ]
内容的提问来源于stack exchange,提问作者Deivid Kutter
相关产品推荐
相关产品推荐

