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

[1, 2, 3, 4]  ⟶  2.5

当前回答

如果您使用的是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,方差,模式,调和平均值,中位数等,这些方法都非常有用。

其他回答

print reduce(lambda x, y: x + y, l)/(len(l)*1.0)

或者像之前写的那样

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

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

作为初学者,我只是编写了这个代码:

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)

使用numpy.mean:

xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]

import numpy as np
print(np.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]

l = map(float,l)
print '%.2f' %(sum(l)/len(l))