Python - 如何让每个项目乘以用户输入的数量?
Python - How to get each item multiplied by the amount the user inputs?
我有这个 python3 代码,它是一个简单的购物清单,用户可以键入他想购买的商品,然后输出就是总成本。但不是多次重复每个项目,我希望用户输入数量,例如...“2chicken,2tomato”而不是“chicken,chicken,tomato,tomato”。我该怎么做?
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。
我会通过以下方式使用 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 EGP
我有这个 python3 代码,它是一个简单的购物清单,用户可以键入他想购买的商品,然后输出就是总成本。但不是多次重复每个项目,我希望用户输入数量,例如...“2chicken,2tomato”而不是“chicken,chicken,tomato,tomato”。我该怎么做?
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。
我会通过以下方式使用 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 EGP