【问题标题】:Python: Finding the average using sum/len after already rounding numbersPython:在舍入数字后使用 sum/len 求平均值
【发布时间】:2020-11-09 01:39:40
【问题描述】:

我正在尝试构建一个程序,用户在该程序中以磅为单位输入地球上的重量(进入 ARRAY)。该程序将重量转换为它在月球上的重量。 然后最后,我希望它获取存储的数组并计算输入重量在月球上的平均重量。

使用下面的代码,它给了我“TypeError: 'float' object is not iterable”。 如何计算平均值?任何帮助表示赞赏! 我的代码在这里link

numlist = list()
lbs = float(input("Enter a weight of person (Enter –1 to exit): "))
while (lbs != -1 ):
    numlist.append(lbs)
    moon_weight = (lbs / 9.81) * 1.622
    limited_float = round(moon_weight)
    print ('This person weighs', limited_float, 'pounds on the moon.')
    lbs = eval(input("Enter a next weight (Enter –1 to exit): "))

average = sum(moon_weight) / len(numlist)
print ('Average of weights on the moon:', average)

编辑: 因为while True 对我来说还是新的,我不想仅仅使用别人的工作。在其他人的大力帮助下,这就是我能够做到的。

numlist = list()
lbs = float(input("Enter a weight of person (Enter –1 to exit): "))
while (lbs != -1 ):
    moon_weight = (lbs / 9.81) * 1.622
    limited_float = round(moon_weight)
    numlist.append(moon_weight)
    print ('This person weighs', limited_float, 'pounds on the moon.')
    lbs = eval(input("Enter a next weight (Enter –1 to exit): "))

average = round(sum(numlist) / len(numlist))
print ('Average of weights on the moon:', average)

【问题讨论】:

    标签: python arrays average


    【解决方案1】:

    您需要将moon_weight 添加到numlist(而不是lbs),然后计算sum(numlist) / len(numlist) 而不是sum(moon_weight) / len(numlist)

    【讨论】:

    • 你能告诉我你说我应该在哪里添加moon_weightnumlist
    • @notsomasterprogrammer 不,我相信你会明白的。这里已经有很多用勺子喂食的答案了。
    • 我很抱歉需要帮助,这是我第一次上编程课。
    • 我宁愿理解我为什么做错事,这样我就可以防止将来发生同样的错误,而不是仅仅接受用勺子喂的答案而不理解所说的更正是否有效。但是“谢谢”
    • @notsomasterprogrammer 我在这里回答问题是为了大家的利益,我不是私人老师(免费)。 “请给我看”或“请教我”不是问题,对除您以外的任何人都没有用处。我的工作不是找出你的知识差距到底在哪里——你到底不明白什么。正如我所说,我相信您会根据这里的答案与您自己的答案进行比较。
    【解决方案2】:

    如果我理解正确,这就是你要找的。 我认为您将变量 moon_weight 与列表 numlist 混淆了。 下面是一个工作示例,说明如何做到这一点。

    moon_weights_list = list()
    while True:
        lbs = float(input("Enter a weight of person (Enter –1 to exit): "))
        if lbs == -1 :
            break
    
        moon_weight = (lbs / 9.81) * 1.622
        moon_weights_list.append(moon_weight)
    
        limited_float = round(moon_weight)
        print ('This person weighs', limited_float, 'pounds on the moon.')
    
    average = sum(moon_weights_list) / len(moon_weights_list)
    print('Average of weights on the moon:', average)
    

    为了指出您遇到的具体问题,我将尝试解释这一行中出现的错误:

    average = sum(moon_weight) / len(numlist)
    

    错误:

    TypeError: 'float' object is not iterable
    

    由函数 sum() 引发,该函数将可迭代对象作为参数。

    • 那么什么是可迭代对象?
    1. 它是实现__iter____next__ 的类的实例。
    2. 一个更简单的定义是:例如 for 循环可以迭代的东西。比如列表、集合、字典、类型等等......

    回到你的代码,sum(moon_weight) 函数将moon_weight 作为参数,它应该包含一个浮点数,(moon_weight = (lbs / 9.81) * 1.622)。

    代码如下:

    average = sum(numlist) / len(numlist)
    

    例如计算输入值的平均值(对于地球而不是月球)。

    接下来是找到一种方法来创建一个包含月球值的列表,然后将其传递给两个函数 sum() 和 len()。正如我在上面包含的代码中所做的那样。

    【讨论】:

    • 这完全符合我的要求。我现在需要弄清楚是什么使这个程序正确,而我的程序不能正常工作。我还没有学习/或不了解while Truebreaks。我会坚持下去,因为我不只是想使用别人的工作。非常感谢!
    • 如果你真的这么想而不是向你致敬,我编辑了帖子并尝试添加更多解释,
    • 非常感谢您指出出了什么问题。我知道我显然没有为平均值选择正确的变量,但我不明白我在混淆什么。根据您的建议,如果我不完全理解,请纠正我,我没有将numlist 中的用户输入元素附加到moon_weight 中这些元素的转换中。因此,当我使用numlist时,并没有使用moon_weight中的计算。
    • 是的,没错。因此,您可以(1)创建一个新列表,然后将转换后的元素附加到它,最后使用它来计算 sum() 和 len() 的平均值或(2)使用 numlist 而不是附加 lbs, u附加 moon_weight 值,然后将其用于 sum() 和 len() 值
    • 非常感谢您的耐心和指导!这对我来说是非常新的,我相当于一个 pre-k 级别的编程。知道我的错误并能够知道错误的原因有助于我更好地理解。如果您想查看它,我已经编辑了我的原始帖子以反映我更正的内容。我将继续利用您使用的方法来提高我的编程能力。
    【解决方案3】:

    更正代码

    numlist = [] # more standard than numlist = list()
    while True:
        # Only need one input
        lbs = input("Enter a weight of person (Enter -1 to exit): ")
        if lbs == '-1' or lbs == '':
            break                           # done on -1 or empty string
        
        lbs = float(lbs)                    # float conversion
        moon_weight = (lbs/9.81)*1.622
        numlist.append(moon_weight)         # add moon weight
        print(f'This person weighs {round(moon_weight)} pounds on the moon')  # using string interpolation  # using string interpolation
    
    # String interpolation and show two decimal places i.e. .2f
    print(f'Average of weights on the moon: {sum(numlist) /len(numlist):.2f}')
    

    测试

    Enter a weight of person (Enter -1 to exit): 100
    This person weighs 17 pounds on the moon
    Enter a weight of person (Enter -1 to exit): 150
    This person weighs 25 pounds on the moon
    Enter a weight of person (Enter -1 to exit): 200
    This person weighs 33 pounds on the moon
    Enter a weight of person (Enter -1 to exit): -1
    Average of weights on the moon: 24.80
    

    说明

    行:

    print(f'Average of weights on the moon: {sum(numlist) /len(numlist):.2f}')
    

    相当于:

    average = sum(numlist) /len(numlist)
    average_fmt = round(average, 2)        # round to 2 decimal places
    print('Average of weights on the moon: ', average_fmt)
    

    那是因为:

    f'Average of weights on the moon: {sum(numlist) /len(numlist):.2f}' 
    

    是一个字符串插值(即允许内部表达式被评估为最终字符串的特殊字符串)。

    String interpolation的信息

    带有 {} 的项目被评估为表达式。 {} 中的“:”标识允许添加格式说明符(例如“.2f”提供两位小数)。

    更简单的 While 循环和输出

    numlist = [] # more standard than numlist = list()
    lbs = ''     # initial value so we will enter while loop
    while lbs != -1:
        lbs = input("Enter a weight of person (Enter -1 to exit): ")
        if lbs != '-1':
          print(lbs)
          lbs = float(lbs)                    # float conversion
          moon_weight = (lbs/9.81)*1.622
          numlist.append(moon_weight)         # add moon weight
          print('This person weighs', round(moon_weight), 'pounds on the moon')  # using string interpolation  # using string interpolation
        else:
            break
         
    if len(numlist) > 0:
        print('Average of weights on the moon: ', round(sum(numlist) /len(numlist), 2))
    else:
        print('No weights entered')
    

    【讨论】:

    • 我没有关注您最后提供的内容如何计算平均值。你能详细说明一下吗?
    • @notsomasterprogrammer——添加了更多解释。这有帮助吗?
    • 确实有道理。我不知道字符串插值。这对我来说太先进了,但我非常感谢你向我介绍了一个新概念。我将来可以使用它!我仍在尝试了解while Truebreaks 的用法。我知道这是标准。我将对此进行更多研究,以帮助我简化程序。也感谢您的伪代码解释。我将开始将这些应用到这个程序和未来的程序中!
    • @notsomasterprogrammer——添加了一个更简单的 while 循环示例。你熟悉这种形式的while循环吗?这不使用字符串插值,但请注意 print 语句中的项目已被分成多个部分。字符串插值避免了这种情况(字符串插值在许多语言中很流行,即string interpolation languages
    • 是的,看起来更熟悉!我知道这不是最有效的编程方式,但我认为这是我现在的水平。如果您想查看它,我已将我的原始帖子编辑为我能够更正并开始工作的内容。非常感谢您的帮助!
    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    相关资源
    最近更新 更多