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

[1, 2, 3, 4]  ⟶  2.5

当前回答

xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)

其他回答

print reduce(lambda x, y: x + y, l)/(len(l)*1.0)

或者像之前写的那样

sum(l)/(len(l)*1.0)

1.0是为了确保你得到一个浮点除法

我想补充另一种方法

import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)

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

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

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

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

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

使用numpy.mean:

xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]

import numpy as np
print(np.mean(xs))