【问题标题】:Calculating values in dict using 'for' loop使用'for'循环计算dict中的值
【发布时间】: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


【解决方案1】:

将您的配额转换为 int

amount=amount+int(quota)

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

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

【讨论】:

    【解决方案2】:

    当您访问amount_in_litres[drink] 时,您将获得str,因为您的字典是:

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

    你想把它改成:

    quota = int(amount_in_litres[drink])
    

    所以quota 将输入int

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-02
        相关资源
        最近更新 更多