如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.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)
其他回答
当Python有一个完美的cromulent sum()函数时,为什么要使用reduce()呢?
print sum(l) / float(len(l))
(float()在Python 2中强制Python执行浮点除法是必需的。)
如果您使用的是python >= 3.4,则有一个统计库
https://docs.python.org/3/library/statistics.html
你可以像这样使用它的mean方法。让我们假设你有一个数字列表,你想找到平均值:-
list = [11, 13, 12, 15, 17]
import statistics as s
s.mean(list)
它还有其他方法,比如stdev,方差,模式,调和平均值,中位数等,这些方法都非常有用。
而不是强制转换为float,你可以将0.0加到和:
def avg(l):
return sum(l, 0.0) / len(l)
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)
结合上面的几个答案,我提出了以下与reduce一起工作的方法,并且不假设你在reduce函数中有L可用:
from operator import truediv
L = [15, 18, 2, 36, 12, 78, 5, 6, 9]
def sum_and_count(x, y):
try:
return (x[0] + y, x[1] + 1)
except TypeError:
return (x + y, 2)
truediv(*reduce(sum_and_count, L))
# prints
20.11111111111111