math - 在Python中计算算术平均值(一种平均值)
Python中是否有内置或标准库方法来计算数字列表的算术平均值(一种平均值)?
12个解决方案
259 votes
我不知道标准库中有什么。 但是,您可以使用以下内容:
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0
在numpy,有numpy.mean()。
NPE answered 2019-02-16T10:06:05Z
176 votes
NumPy的numpy.mean是算术平均值。 用法就像这样简单:
>>> import numpy
>>> a = [1, 2, 4]
>>> numpy.mean(a)
2.3333333333333335
Bengt answered 2019-02-16T10:06:30Z
160 votes
在Python 3.4中,有一个新的statistics模块。 您现在可以使用statistics:
import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335
对于3.1-3.3用户,模块的原始版本在PyPI上可用,名称为statistics.只需将statistics更改为stats。
kirbyfan64sos answered 2019