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

[1, 2, 3, 4]  ⟶  2.5

当前回答

如果您使用的是python >= 3.4,则有一个统计库

https://docs.python.org/3/library/statistics.html

你可以像这样使用它的mean方法。让我们假设你有一个数字列表,你想找到平均值:-

list = [11, 13, 12, 15, 17]
import statistics as s
s.mean(list)

它还有其他方法,比如stdev,方差,模式,调和平均值,中位数等,这些方法都非常有用。

其他回答

结合上面的几个答案,我提出了以下与reduce一起工作的方法,并且不假设你在reduce函数中有L可用:

from operator import truediv

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

def sum_and_count(x, y):
    try:
        return (x[0] + y, x[1] + 1)
    except TypeError:
        return (x + y, 2)

truediv(*reduce(sum_and_count, L))

# prints 
20.11111111111111

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

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

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

假设

x = [
    [-5.01,-5.43,1.08,0.86,-2.67,4.94,-2.51,-2.25,5.56,1.03],
    [-8.12,-3.48,-5.52,-3.78,0.63,3.29,2.09,-2.13,2.86,-3.33],
    [-3.68,-3.54,1.66,-4.11,7.39,2.08,-2.59,-6.94,-2.26,4.33]
]

你可以注意到x的维数是3*10如果你需要得到每一行的平均值,你可以输入这个

theMean = np.mean(x1,axis=1)

不要忘记将numpy导入为np

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

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

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