【问题标题】:How to return stuff from the dictionary and multiply them all?如何从字典中返回东西并将它们全部相乘?
【发布时间】:2021-11-19 17:38:03
【问题描述】:

因此,我尝试将分配给字典 output 中每个变量的每个数字相乘,并创建了一个函数 totalcalories(inputlst) 来查找它。

所以我想做的是定义一个函数totalcalories(inputlst),它将根据你吃的每餐返回消耗的卡路里总数。

卡路里将像这样存储在字典中......

inputlst =  {"Cabbage":"4,2,0", "Carrot":"9,1,5", "Fatty Pork":"431,1,5"}

第一个数字乘以 5,第二个数字乘以 5,第三个数字乘以 9。

例如,如果调用Cabbage,(它的数字是(4,2,0)),输出应该返回((4 * 5)+(2 * 5)+(0 * 9)),也就是 30。

我试过这样做,显然行不通……

def totalcalories(inputlist):
    output = {inputlist}
    g= []
    for x in output:
        g.append(x)
    return g
print(totalcalories(["Cabbage"]))

我真的很陌生,所以请尝试使用字典和简单的初学者编程技巧来帮助我,谢谢:)

【问题讨论】:

  • 我很困惑:输出应该如何返回 ((45)+(25)+(0*9)),即 30. 工作?
  • 这是一个错字对不起..我使用 (*) ,它本来是一个乘号,但它不知何故被改变了..我修复了它
  • @nikeros 其 (4 乘 5) + (2 乘 5) + ( 0 乘 9),即 20 + 10 + 0 = 30

标签: python list


【解决方案1】:

你可以这样使用:

sum([x*y for x, y in zip(map(int, inputlst["Cabbage"].split(",")),[5,5,9])])

基本上,在将输入列表解析为整数后,您会并排获得它们各自的乘数,并使用列表推导将它们相乘。

函数是:

def calc(name):
    return sum([x*y for x, y in zip(map(int, inputlst[name].split(",")),[5,5,9])])

【讨论】:

  • 像你建议的一个班轮真的很难阅读/理解。我建议将其分步拆分,以便 OP 也知道每个步骤的作用。因为他明确指出“简单的初学者编程技巧”。
  • @ThePjot 点,你知道,这是一个很好的平衡:你不希望你的代码太冗长,但同时它应该是自我解释的。在这个特定的案例中,我认为这是一个简单的one liner,对于一个简单的任务只需要几个操作。你应该看过我以前用 Perl 写的东西 :-D。就学习而言:当我在这个网站上找到一个有趣的解决方案时,我会自己剖析它,这才是你真正学习的方式——否则它就像一本书......
【解决方案2】:

您的代码尝试目前没有执行您希望它执行的任何操作,因此最好从头开始。

首先,您需要一个函数,该函数将接受输入的食物(作为字符串)和您的字典 inputlst,因此我们可以从以下内容开始:

def totalcalories(food, inputlst):
    #calculate calories

首先,您需要能够访问与您的字典中的食物键关联的值。你可以这样做:

inputlst['Cabbage']

返回:

'4,2,0'

您的字典值都是数字字符串,这使事情变得更加复杂。如果您可以将它们作为列表,例如,使用这些数字会更容易。 [4, 2, 0],但我们可以将字符串更改为列表并删除“,”,如下所示:

values = list(inputlst[food])
values = [x for x in values if x != ',']

所以现在您有了一个可以使用的值列表,所以现在将每个值乘以您在上面指定的值(5、5 和 9)。如果它们可能发生变化,将它们作为变量添加到您的函数中可能会很有用,但现在我将其编写如下:

output = (values[0] * 5) + (values[1] * 5) + (values[2] * 9)

然后您需要将return output 添加到函数的末尾。希望这些信息足以让您现在能够组合您的函数。

【讨论】:

    【解决方案3】:

    我不确定您是否可以控制输入列表。但如果你这样做,请尝试将其转换为整数列表,而不是逗号分隔的字符串。为什么?它需要一个额外的步骤来将其转换为整数以进行乘法操作。

    所以把它变成这样:

    inputlst =  {"Cabbage":[4, 2, 0], "Carrot":[9, 1, 5], "Fatty Pork":[431, 1, 5]}
    

    如果您无法直接转换,您可以使用map 轻松地将您的输入转换为:

    inputlst =  {"Cabbage":"4,2,0", "Carrot":"9,1,5", "Fatty Pork":"431,1,5"}
    # Loop over all key and value in your dict.
    for key, value in inputlst.items():
        # Split string into the separate numbers.
        new_value = value.split(',')
        # Convert them into integers using ma[.
        # map returns a map object, convert it into a list.
        inputlst[key] = list(map(int, new_value))
    
    print(inputlst) # {'Cabbage': [4, 2, 0], 'Carrot': [9, 1, 5], 'Fatty Pork': [431, 1, 5]}
    

    然后在您的代码中,您不需要对数据进行任何转换。让自己更轻松并保持简单(KISS 方法):

    # Define a constant with our multipliers.
    MULTIPLIERS = [5, 5, 9]
    
    
    def totalcalories(list_of_integers):
        total = 0
        # Loop over the integers and keep track of the index of the loop.
        for i, integer_value in enumerate(list_of_integers):
            # Fetch the multiplier we want for this index.
            multiplier = MULTIPLIERS[i]
            # Apply multiply and add it to the total.
            total += (integer_value * multiplier)
        return total
    

    然后我们可以轻松地在 for 循环中调用:

    >>> for key, value in inputlst.items():
    >>>     print(key, totalcalories(value))
    Cabbage 30
    Carrot 95
    Fatty Pork 2205
    

    或者当然只是你想要的值:

    >>> totalcalories(inputlst['Cabbage'])
    30
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      相关资源
      最近更新 更多