如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
当前回答
而不是强制转换为float,你可以将0.0加到和:
def avg(l):
return sum(l, 0.0) / len(l)
其他回答
两者都可以在一个整数或至少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的说法是正确的。
对于Python 3.8+,使用统计信息。浮点数稳定性的平均值。(快)。
对于Python 3.4+,使用统计信息。平均数值稳定性与浮子。(慢)。
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(xs) # = 20.11111111111111
对于较旧版本的Python 3,请使用
sum(xs) / len(xs)
对于Python 2,将len转换为浮点数以获得浮点除法:
sum(xs) / float(len(xs))
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)
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
在Udacity的问题中,我也有一个类似的问题要解决。而不是一个内置的函数,我编码:
def list_mean(n):
summing = float(sum(n))
count = float(len(n))
if n == []:
return False
return float(summing/count)
比平时长得多,但对于初学者来说,这是相当具有挑战性的。