如何在Python中找到列表的平均值?

[1, 2, 3, 4]  ⟶  2.5

当前回答

当Python有一个完美的cromulent sum()函数时,为什么要使用reduce()呢?

print sum(l) / float(len(l))

(float()在Python 2中强制Python执行浮点除法是必需的。)

其他回答

对于Python 3.4+,使用新的统计模块中的mean()来计算平均值:

from statistics import mean
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
mean(xs)
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]

l = map(float,l)
print '%.2f' %(sum(l)/len(l))

对于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))

当Python有一个完美的cromulent sum()函数时,为什么要使用reduce()呢?

print sum(l) / float(len(l))

(float()在Python 2中强制Python执行浮点除法是必需的。)

而不是强制转换为float,你可以将0.0加到和:

def avg(l):
    return sum(l, 0.0) / len(l)