【问题标题】:assistance needed please, float is not iterable issues请需要帮助,浮动不是可迭代的问题
【发布时间】:2022-12-03 12:14:56
【问题描述】:

`

life_max = -5
life_min = 999
country_max = ""
country_min = ""

answer = int(input("Which year would you like to enter? "))


with open ("life.csv") as f:
    next(f)
    


    for line in f:
        parts = line.split(",")
        life = float(parts[3])
        year = int(parts[2])
        country = parts[0].strip()
        code = parts[1].strip()

        

        if life > life_max:
            life_max = life
            country_max = country
        if life < life_min:
            life_min = life
            country_min = country
    average = range(sum(life)) / range(len(life))
    print(f"The average is {average}")
    print(f"The country with the worst life expectancy is {country_min} at {life_min} years.")
    print(f"The country with the best life expectancy is {country_max} at {life_max} years.")

`

我在查找指定年份的平均预期寿命时遇到了一些麻烦,它返回时出现“浮动”不可迭代错误,我很迷茫。

【问题讨论】:

  • 哪一行代码导致错误?它应该在错误上方这样说,您可以在此处发布错误的整个堆栈跟踪以供我们查看
  • lifefloat。您期望sum(life) 是什么?
  • life 是一个单身的float。你希望sum(life)做什么?你可能想要收集所有值列表中的 life,然后求和那个清单.

标签: python python-3.x


【解决方案1】:

sum 需要单个值才能工作,而不是列表或字典;) sum 只是添加单个值并返回结果。

【讨论】:

    【解决方案2】:

    在没有您的输入和哪一行抛出错误的情况下回答这个问题有点令人困惑,但我猜这是由于'sum(life)' - life 似乎是一个浮点数,而 sum 期望一个可迭代的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多