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

[1, 2, 3, 4]  ⟶  2.5

当前回答

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

享受。

其他回答

使用numpy.mean:

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

import numpy as np
print(np.mean(xs))

Sum (l) / float(len(l))是正确答案,但为了完整起见,你可以用一个reduce来计算平均值:

>>> reduce(lambda x, y: x + y / float(len(l)), l, 0)
20.111111111111114

注意,这可能会导致轻微的舍入误差:

>>> sum(l) / float(len(l))
20.111111111111111

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

两者都可以在一个整数或至少10个十进制值上给出接近的值。但如果你真的考虑长浮动值,这两者可能是不同的。方法可以根据你想要达到的目标而有所不同。

>>> 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

浮动值

>>> print reduce(lambda x, y: x + y, l) / float(len(l))
20.1111111111
>>> print sum(l)/float(len(l))
20.1111111111

@Andrew Clark的说法是正确的。

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

享受。