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

[1, 2, 3, 4]  ⟶  2.5

当前回答

假设

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

两者都可以在一个整数或至少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)