如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.5
如何在Python中找到列表的平均值?
[1, 2, 3, 4] ⟶ 2.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)
其他回答
简单的解决方案是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
享受。
假设
x = [
[-5.01,-5.43,1.08,0.86,-2.67,4.94,-2.51,-2.25,5.56,1.03],
[-8.12,-3.48,-5.52,-3.78,0.63,3.29,2.09,-2.13,2.86,-3.33],
[-3.68,-3.54,1.66,-4.11,7.39,2.08,-2.59,-6.94,-2.26,4.33]
]
你可以注意到x的维数是3*10如果你需要得到每一行的平均值,你可以输入这个
theMean = np.mean(x1,axis=1)
不要忘记将numpy导入为np
在Udacity的问题中,我也有一个类似的问题要解决。而不是一个内置的函数,我编码:
def list_mean(n):
summing = float(sum(n))
count = float(len(n))
if n == []:
return False
return float(summing/count)
比平时长得多,但对于初学者来说,这是相当具有挑战性的。
你可以为平均值,使用率做一个函数:
average(21,343,2983) # You can pass as many arguments as you want.
代码如下:
def average(*args):
total = 0
for num in args:
total+=num
return total/len(args)
*args允许任意数量的答案。
或者使用熊猫系列。意思是方法:
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