如何在Python中找到列表的平均值?

[1, 2, 3, 4]  ⟶  2.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

其他回答

而不是强制转换为float,你可以将0.0加到和:

def avg(l):
    return sum(l, 0.0) / len(l)
print reduce(lambda x, y: x + y, l)/(len(l)*1.0)

或者像之前写的那样

sum(l)/(len(l)*1.0)

1.0是为了确保你得到一个浮点除法

在列表中求平均值 通过使用以下PYTHON代码:

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(sum(l)//len(l))

试着简单一点。

或者使用熊猫系列。意思是方法:

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

我想补充另一种方法

import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)