如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
当前回答
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)
其他回答
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
l = map(float,l)
print '%.2f' %(sum(l)/len(l))
而不是强制转换为float,你可以将0.0加到和:
def avg(l):
return sum(l, 0.0) / len(l)
我想补充另一种方法
import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)
Sum (l) / float(len(l))是正确答案,但为了完整起见,你可以用一个reduce来计算平均值:
>>> reduce(lambda x, y: x + y / float(len(l)), l, 0)
20.111111111111114
注意,这可能会导致轻微的舍入误差:
>>> sum(l) / float(len(l))
20.111111111111111
两者都可以在一个整数或至少10个十进制值上给出接近的值。但如果你真的考虑长浮动值,这两者可能是不同的。方法可以根据你想要达到的目标而有所不同。
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> print reduce(lambda x, y: x + y, l) / len(l)
20
>>> sum(l)/len(l)
20
浮动值
>>> print reduce(lambda x, y: x + y, l) / float(len(l))
20.1111111111
>>> print sum(l)/float(len(l))
20.1111111111
@Andrew Clark的说法是正确的。