如何在Python枚举购物列表时调用字典中的价格值
实现购物篮商品与价格同步输出
你可以直接通过价格字典的键取值,结合字符串格式化来实现需求,修改后的代码如下:
health_supplement_menu = [ "Black Mamba Bulbine", "SA Nutrition Vaccine OCS", "sem10", "S.A.N High Strength CBD 30%", "Pure Shilajat Resin", ] health_supplement_prices = { health_supplement_menu[0]: 18.99, health_supplement_menu[1]: 23.99, health_supplement_menu[2]: 95.00, health_supplement_menu[3]: 49.99, health_supplement_menu[4]: 25.00, } shopping_list = ["sem10", "Pure Shilajat Resin"] print("Basket:\n") for i, item in enumerate(shopping_list, 1): # 从价格字典中获取对应商品的价格 item_price = health_supplement_prices[item] # 用f-string格式化输出序号、商品名和价格 print(f"{i}: - {item} - ¥{item_price:.2f}")
关键说明:
- 因为
shopping_list中的元素都是health_supplement_prices字典的有效键,所以直接用health_supplement_prices[item]就能取出对应价格。 :.2f是格式化语法,确保价格显示为两位小数,符合货币的常规展示方式。
容错优化(可选)
如果后续代码可能出现购物篮商品不在价格字典中的情况,可以用get()方法避免报错:
for i, item in enumerate(shopping_list, 1): # 若商品不存在,返回默认值"价格未知" item_price = health_supplement_prices.get(item, "价格未知") print(f"{i}: - {item} - {item_price}")
内容的提问来源于stack exchange,提问作者user22966617
相关产品推荐
相关产品推荐

