如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
当前回答
或者使用熊猫系列。意思是方法:
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
其他回答
结合上面的几个答案,我提出了以下与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
简单的解决方案是avmedii -lib
pip install avemedi_lib
而不是包括在你的剧本中
from avemedi_lib.functions import average, get_median, get_median_custom
test_even_array = [12, 32, 23, 43, 14, 44, 123, 15]
test_odd_array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Getting average value of list items
print(average(test_even_array)) # 38.25
# Getting median value for ordered or unordered numbers list
print(get_median(test_even_array)) # 27.5
print(get_median(test_odd_array)) # 27.5
# You can use your own sorted and your count functions
a = sorted(test_even_array)
n = len(a)
print(get_median_custom(a, n)) # 27.5
享受。
而不是强制转换为float,你可以将0.0加到和:
def avg(l):
return sum(l, 0.0) / len(l)
我尝试使用上面的选项,但没有工作。 试试这个:
from statistics import mean
n = [11, 13, 15, 17, 19]
print(n)
print(mean(n))
使用过python 3.5
如果你想要的不仅仅是平均值(又名平均),你可以看看scipy的统计:
from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))
# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111,
# variance=572.3611111111111, skewness=1.7791785448425341,
# kurtosis=1.9422716419666397)