Calculating arithmetic mean (average) in Python
Python中是否有内置或标准库方法来计算数字列表的算术平均值(平均值)?
I am not aware of anything in the standard library. However, you could use something like:
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0
In numpy, there's numpy.mean()
.
NumPy has a numpy.mean
which is an arithmetic mean. Usage is as simple as this:
>>> import numpy
>>> a = [1, 2, 4]
>>> numpy.mean(a)
2.3333333333333335
In Python 3.4, there is a new statistics
module. You can now use statistics.mean
:
import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335
For 3.1-3.3 users, the original version of the module is available on PyPI under the name stats
. Just change statistics
to stats
.
上一篇: 检查列表是否为空而不使用`not`命令
下一篇: 在Python中计算算术平均值(平均值)