如何使用for循环计算python数字列表的平均值?

sim*_*sim 0 python for-loop mean python-2.7

尝试使用 for 循环来计算列表的平均值,就像我想练习的那样。

此代码在测试用例中返回 4、5 和 1。有人可以告诉我我做错了什么吗?

def list_mean(p):
total = 0
i = 0
if i < len(p):
    for t in p:
        total = total + p[i]
        i += 1
    return i

mean = i / len(p)
return mean


print list_mean([1,2,3,4])
>>> 2.5

print list_mean([1,3,4,5,2])
>>> 3.0

print list_mean([2])
>>> 2.0
Run Code Online (Sandbox Code Playgroud)

sta*_*eep 5

首先,return i我猜你做了一些无意的事情。

其次,你做i / len(p)而不是total / len(p).

我们可以更进一步,去掉不必要的部分。由于如果等于零for则将跳过循环,因此我们可以删除语句。另外,我们不需要变量,因为 Python循环会一一生成每个元素。因此,您可以使用来代替. 可能这里的最后一件事相当于本例中的内容。len(p)if i < len(p)ifortotal = total + ttotal = total + p[i]total = total + ttotal += t

如果你解决了我提到的所有问题,你应该得到类似的结果:

def list_mean(p):
     total = 0.0
     for t in p:
         total += t
     mean = total / len(p)
     return mean
Run Code Online (Sandbox Code Playgroud)

但如果你想计算平均值,你可以使用这个:

mean = sum(p) / len(p)
Run Code Online (Sandbox Code Playgroud)

请注意,对于 Python 2,您需要将类型显式转换为float

mean = float(sum(p)) / len(p)
Run Code Online (Sandbox Code Playgroud)

  • 您还可以提到变量“i”和“if”语句都不需要。 (2认同)