继续获得'浮动'对象是不可迭代的

时间:2017-08-30 01:05:58

标签: python

numbers = []

while True:
    n = float(input("Enter a number: "))
    if n < 0:
        break
    numbers.append(n)
    Mean = sum(numbers)/len(numbers)

    for xi in numbers:
        var = sum((xi - Mean) ** 2)
        if len(numbers) == 1:
            Variance = var
        else:
            Variance = var/(len(numbers) - 1)
    print(Mean, Variance)

它可以解决均值,但不能解决方差。谢谢!

2 个答案:

答案 0 :(得分:1)

你的var实现是不正确的,你必须首先对这些值进行累积,然后将它们分配到循环之外。 (您使用的sum()函数不会这样做,它会尝试将序列的元素添加到一起。)

numbers = []

while True:
    n = float(input("Enter a number: "))
    if n < 0:
        break
    numbers.append(n)
    Mean = sum(numbers)/len(numbers)
var = 0
for xi in numbers:
    var += (xi - Mean) ** 2

if len(numbers) == 1:
    Variance = var
else:
    Variance = var/(len(numbers) - 1)

print(Mean, Variance)

答案 1 :(得分:0)

您的代码:

var = sum((xi-Mean)**2)

不是获得方差的正确方法,因为sum()函数在每个循环中只合计一个数字,获得每个数字之和的最佳方法是:

var += (xi - Mean) ** 2

所以代码应该是:

while True:
    n = float(input())
    if n < 0:
        break
    numbers.append(n)
    Mean = sum(numbers)/len(numbers)
    var = 0
    for xi in numbers:
        var += (xi-Mean)**2
    if len(numbers) == 1:
        Variance = var
    else:
        Variance = var/(len(numbers)-1)
    print(Mean, Variance)