Python中是否有内置或标准的库方法来计算一组数字的算术平均值(一种平均值)?
当前回答
def list_mean(nums):
sumof = 0
num_of = len(nums)
mean = 0
for i in nums:
sumof += i
mean = sumof / num_of
return float(mean)
其他回答
我不知道标准库中的任何东西。然而,你可以使用这样的东西:
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0
在numpy中,有numpy.mean()。
使用scipy:
import scipy;
a=[1,2,4];
print(scipy.mean(a));
NumPy有一个NumPy。这是算术平均数。用法如下:
>>> import numpy
>>> a = [1, 2, 4]
>>> numpy.mean(a)
2.3333333333333335
from statistics import mean
avarage=mean(your_list)
例如
from statistics import mean
my_list=[5,2,3,2]
avarage=mean(my_list)
print(avarage)
结果是
3.0
def avg(l):
"""uses floating-point division."""
return sum(l) / float(len(l))
例子:
l1 = [3,5,14,2,5,36,4,3]
l2 = [0,0,0]
print(avg(l1)) # 9.0
print(avg(l2)) # 0.0