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

[1, 2, 3, 4]  ⟶  2.5

当前回答

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

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

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

其他回答

或者使用熊猫系列。意思是方法:

pd.Series(sequence).mean()

演示:

>>> import pandas as pd
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> pd.Series(l).mean()
20.11111111111111
>>> 

从文档中可以看出:

系列。意思是(axis= no, skipna= no, level= no, numic_only = no, kwargs

这里是这个的文档:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mean.html

整个文档:

https://pandas.pydata.org/pandas-docs/stable/10min.html

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

from statistics import mean
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
mean(xs)
print reduce(lambda x, y: x + y, l)/(len(l)*1.0)

或者像之前写的那样

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

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

如果你想要的不仅仅是平均值(又名平均),你可以看看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)

在Udacity的问题中,我也有一个类似的问题要解决。而不是一个内置的函数,我编码:

def list_mean(n):

    summing = float(sum(n))
    count = float(len(n))
    if n == []:
        return False
    return float(summing/count)

比平时长得多,但对于初学者来说,这是相当具有挑战性的。