我有这个python3代码,它是一个简单的购物清单,用户可以键入他想要购买的商品,然后输出就是总成本。但是,我不想多次重复每个项目,我希望用户输入的数量像.“2鸡,2番茄”而不是“鸡,鸡,番茄,番茄”,..how,我要这样做吗?
items_dict={"chicken": 50, "fish":30, "tomato":12, "chips":5}
print("Our shop has", tuple(items_dict))
prompt=input("What will you buy?\n").split(', ')
total_price=0
for items in prompt:
try:
total_price += items_dict[items]
except:
total_price="Some items aren't available to buy."
break
print ("You have to pay", total_price, "EGP")输入:2只鸡,22只番茄,100片
预期产出:您必须支付864 EGP。
发布于 2022-05-13 04:53:19
我应该以以下方式使用re.match来处理这个问题:
import re
items_dict={"chicken": 50, "fish":30, "tomato":12, "chips":5}
print("Our shop has", tuple(items_dict))
prompt=input("What will you buy?\n").split(', ')
total_price=0
for items in prompt:
match = re.match("(\d+)(\w+)", items) # Here group(1) => (\d+) will match the quantity of item and
# group(2) => (\w+) will match the name of product.
try:
total_price += (int(match.group(1))*items_dict[match.group(2)])
except:
total_price="Some items aren't available to buy."
print ("You have to pay", total_price, "EGP")输出:
Our shop has ('chicken', 'fish', 'tomato', 'chips')
What will you buy?
2chicken, 22tomato, 100chips
You have to pay 864 EGPhttps://stackoverflow.com/questions/72224508
复制相似问题