如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
当前回答
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
l = map(float,l)
print '%.2f' %(sum(l)/len(l))
其他回答
对于Python 3.4+,使用新的统计模块中的mean()来计算平均值:
from statistics import mean
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
mean(xs)
使用numpy.mean:
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import numpy as np
print(np.mean(xs))
如果您使用的是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,方差,模式,调和平均值,中位数等,这些方法都非常有用。
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
l = map(float,l)
print '%.2f' %(sum(l)/len(l))
如果你想要的不仅仅是平均值(又名平均),你可以看看scipy的统计:
from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))
# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111,
# variance=572.3611111111111, skewness=1.7791785448425341,
# kurtosis=1.9422716419666397)