使用 'for' 循环计算字典中的值

Calculating values in dict using 'for' loop

我是 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[drink] 时,您会得到 str,因为您的字典是:

amount_in_litres = { "soda": "550", "tea": "500", "water": "1200", "coffee": "720" }

您想将其更改为:

quota = int(amount_in_litres[drink])

所以 quota 将被输入 int

将您的配额转换为整数

amount=amount+int(quota)

如果你想要总共一行,那么请取消缩进(删除循环内的打印语句,因为它会在每次循环迭代时打印)并在循环外打印

for brand in brandnames:
    drink = drinks[brand]      
    quota = amount_in_litres[drink] 
    amount = amount + int (quota)
print(amount, "litres consumed.")

您的 amount_in_litres 字典包含数字作为字符串,例如“550”。用不带引号的数字替换它们,例如550.