首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python --如何将每个项目乘以用户输入的数量?

Python --如何将每个项目乘以用户输入的数量?
EN

Stack Overflow用户
提问于 2022-05-13 04:37:13
回答 1查看 43关注 0票数 0

我有这个python3代码,它是一个简单的购物清单,用户可以键入他想要购买的商品,然后输出就是总成本。但是,我不想多次重复每个项目,我希望用户输入的数量像.“2鸡,2番茄”而不是“鸡,鸡,番茄,番茄”,..how,我要这样做吗?

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-13 04:53:19

我应该以以下方式使用re.match来处理这个问题:

代码语言:javascript
复制
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")

输出:

代码语言:javascript
复制
Our shop has ('chicken', 'fish', 'tomato', 'chips')
What will you buy?
2chicken, 22tomato, 100chips
You have to pay 864 EGP
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72224508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档