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

[1, 2, 3, 4]  ⟶  2.5

当前回答

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

其他回答

xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)
print reduce(lambda x, y: x + y, l)/(len(l)*1.0)

或者像之前写的那样

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

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

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

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]

total = 0

def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

print average(L)

简单的解决方案是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

享受。