如何在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)
其他回答
作为初学者,我只是编写了这个代码:
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 3.8+,使用统计信息。浮点数稳定性的平均值。(快)。
对于Python 3.4+,使用统计信息。平均数值稳定性与浮子。(慢)。
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(xs) # = 20.11111111111111
对于较旧版本的Python 3,请使用
sum(xs) / len(xs)
对于Python 2,将len转换为浮点数以获得浮点除法:
sum(xs) / float(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
print reduce(lambda x, y: x + y, l)/(len(l)*1.0)
或者像之前写的那样
sum(l)/(len(l)*1.0)
1.0是为了确保你得到一个浮点除法
如果您使用的是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,方差,模式,调和平均值,中位数等,这些方法都非常有用。