如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
当前回答
我尝试使用上面的选项,但没有工作。 试试这个:
from statistics import mean
n = [11, 13, 15, 17, 19]
print(n)
print(mean(n))
使用过python 3.5
其他回答
作为初学者,我只是编写了这个代码:
L = [15, 18, 2, 36, 12, 78, 5, 6, 9]
total = 0
def average(numbers):
total = sum(numbers)
total = float(total)
return total / len(numbers)
print average(L)
print reduce(lambda x, y: x + y, l)/(len(l)*1.0)
或者像之前写的那样
sum(l)/(len(l)*1.0)
1.0是为了确保你得到一个浮点除法
对于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))
而不是强制转换为float,你可以将0.0加到和:
def avg(l):
return sum(l, 0.0) / len(l)