【问题标题】:Sum List of Elements Using Index of List [duplicate]使用列表索引对元素求和列表 [重复]
【发布时间】:2018-12-24 14:41:30
【问题描述】:

我试图找出厨房(18.0)和卧室面积(10.75)的总和

# Create the areas list
 areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 
10.75, "bathroom", 9.50]

 # Sum of kitchen and bedroom area: eat_sleep_area
 eat_sleep_area = sum(areas[3],areas[-3])

 # Print the variable eat_sleep_area
 print(eat_sleep_area)

但是当我尝试运行代码时,它会说: TypeError:“浮动”对象不可迭代 我还观察到,当我使用 min,max 等其他函数时,它工作得很好 谁能解释一下这是什么原因?

【问题讨论】:

  • sum 的第一项应该是可迭代的。你正在通过浮动。您只需将它们加在一起即可。
  • 如果你想添加两个或更多变量为什么不使用 + 运算符?!
  • 试试例子 area_map = dict(zip(areas[::2], area[1::2])) eat_sleep_area = area_map['hallway'] + area_map['living room'] area_tup = tuple(zip(areas[::2], area[1::2])) area_tup[3][1] + area_tup[-3][1]

标签: python python-3.x indexing sum


【解决方案1】:

你需要使用字典而不是列表来处理这种事情:

areas = {
    'hallway': 11.25,
    'kitchen': 18.0,
    'living room': 20.0,
    'bedroom': 10.75,
    'bathroom': 9.50,
}

然后你可以像这样总结它们:

result = areas['kitchen'] + areas['bedroom']

字典允许按键查找。 Check the docs 了解更多。

【讨论】:

    【解决方案2】:

    在 Python 中,sum(iterable[, start]) 需要可迭代作为第一个参数。考虑将您的论点包装在如下列表中:

    sum([areas[3],areas[-3]])
    

    【讨论】:

      【解决方案3】:

      如果你使用字典会更好:

      areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
      areas = { name : measures for name, measures in zip(areas, areas[1:])}
      result = sum(areas[name] for name in ('kitchen', 'bedroom'))
      print(result)
      

      输出

      28.75
      

      【讨论】:

        【解决方案4】:

        sum() 函数从左到右添加给定迭代的开始和项。

        sum() 参数 iterable - 要查找其项目总和的可迭代(列表、元组、字典等)。通常,可迭代的项目应该是数字。 start (可选) - 此值被添加到可迭代项的总和中。 start 的默认值为 0(如果省略)

        浮点数不可迭代

        【讨论】:

          【解决方案5】:

          可以用add操作符替换sum

          from operator import add
          eat_sleep_area = add(areas[3],areas[-3]) # if you have only two entities to add otherwise use sum and pass an iterator
          

          或加总

          eat_sleep_area = add([areas[3],areas[-3]])
          

          【讨论】:

            猜你喜欢
            • 2014-10-26
            • 2018-07-06
            • 1970-01-01
            • 1970-01-01
            • 2018-09-17
            • 2021-04-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多