例如,我正在开发一个程序来获取商店中订购的商品总数。我为可用项目创建了一个名为menu的字典,但是如果订单列表中订购的项目不在我的词典“菜单”的键名范围之内,则应将该项目替换为Coke。
我的意图是将项目转换为它们的价格,这是字典中的相应值,然后进行必要的总计。
但是似乎像在示例中一样,爆米花并没有让步。请帮助。
a = ["Pizza", "Cheeseburger", "Water", "Popcorn"]
menu = {"Nachos":6,"Pizza":6,"Cheeseburger":10,"Water":4,"Coke":5}
for i in a:
if not i in menu:
i = "Coke"
print(a)
参考方案
i
变量仅表示可迭代对象中的当前项,要替换数组中的值,可以使用其索引,enumerate
给出元组(index, element)
order = ["Pizza", "Cheeseburger", "Water", "Popcorn"]
menu = {"Nachos": 6, "Pizza": 6, "Cheeseburger": 10, "Water": 4, "Coke": 5}
for idx, item in enumerate(order):
if item not in menu:
order[idx] = "Coke"
print(order) # ['Pizza', 'Cheeseburger', 'Water', 'Coke']
但是您将在接下来寻找价格,您可以在同一张照片中完成
total = 0
for item in order:
total += menu.get(item, menu["Coke"]) # if item not present, get price of Coke
print(total)
Python-crontab模块 - python我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…
Python Pandas导出数据 - python我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…
Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
每个文件合并后添加换行 - python我有很多类似以下内容的JSON文件:例如。1.json{"name": "one", "description": "testDescription...", "comment": ""} test.json{"name"…