如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
当前回答
对于Python 3.4+,使用新的统计模块中的mean()来计算平均值:
from statistics import mean
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
mean(xs)
其他回答
或者使用熊猫系列。意思是方法:
pd.Series(sequence).mean()
演示:
>>> import pandas as pd
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> pd.Series(l).mean()
20.11111111111111
>>>
从文档中可以看出:
系列。意思是(axis= no, skipna= no, level= no, numic_only = no, kwargs
这里是这个的文档:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mean.html
整个文档:
https://pandas.pydata.org/pandas-docs/stable/10min.html
作为初学者,我只是编写了这个代码:
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)
我想补充另一种方法
import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)
结合上面的几个答案,我提出了以下与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
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)