I have to find the average of a list in Python. This is my code so far
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)
I want to add just another approach
import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)
Or use pandas
's Series.mean
method:
pd.Series(sequence).mean()
Demo:
>>> import pandas as pd
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> pd.Series(l).mean()
20.11111111111111
>>>
From the docs:
Series.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
¶
And here is the docs for this:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mean.html
And the whole documentation:
https://pandas.pydata.org/pandas-docs/stable/10min.html
Both can give you close to similar values on an integer or at least 10 decimal values. But if you are really considering long floating values both can be different. Approach can vary on what you want to achieve.
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> print reduce(lambda x, y: x + y, l) / len(l)
20
>>> sum(l)/len(l)
20
Floating values
>>> print reduce(lambda x, y: x + y, l) / float(len(l))
20.1111111111
>>> print sum(l)/float(len(l))
20.1111111111
@Andrew Clark was correct on his statement.
I tried using the options above but didn't work. Try this:
from statistics import mean
n = [11, 13, 15, 17, 19]
print(n)
print(mean(n))
worked on python 3.5
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)