【发布时间】:2021-04-04 20:41:36
【问题描述】:
我是 Python 新手,我正在尝试解决以下任务:我需要使用以下信息计算以升为单位消耗的 Fanta、Lavazza、Lipton 等的总量(正确答案为 7140 升) :
brandnames = { "Fanta", "Lavazza", "Lipton", "Coke", "Evian", "Nescafe", "Twinings", "Volvic",
"Perrier" }
drinks = { "Fanta": "soda", "Lavazza": "coffee", "Lipton": "tea", "Coke": "soda", "Evian": "water",
"Nescafe": "coffee", "Twinings": "tea", "Volvic": "water", "Perrier": "water" }
type = { "soda", "tea", "coffee", "water" }
amount_in_litres = { "soda": "550", "tea": "500", "water": "1200", "coffee": "720" }
我尝试了以下方法:
amount = 0
for brand in brandnames:
drink = drinks[brand]
quota = amount_in_litres[drink]
amount = amount + quota
print(amount, "litres consumed.")
但我收到以下错误消息:+ 的不支持的操作数类型:'int' 和 'str'。我什至不确定我是否应该包含一个 if 语句来解决问题或我应该做什么。我究竟做错了什么?如果有人可以提供帮助,请提前致谢。
【问题讨论】:
-
amount _in_litres 以字符串格式存储值。您不能将金额(整数类型)与配额(字符串类型)相加。在添加前将配额转换为整数格式。
标签: python dictionary calculation