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

[1, 2, 3, 4]  ⟶  2.5

当前回答

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

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

试着简单一点。

其他回答

我尝试使用上面的选项,但没有工作。 试试这个:

from statistics import mean

n = [11, 13, 15, 17, 19]

print(n)
print(mean(n))

使用过python 3.5

两者都可以在一个整数或至少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的说法是正确的。

你可以为平均值,使用率做一个函数:

average(21,343,2983) # You can pass as many arguments as you want.

代码如下:

def average(*args):
    total = 0
    for num in args:
        total+=num
    return total/len(args)

*args允许任意数量的答案。

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

或者像之前写的那样

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

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

结合上面的几个答案,我提出了以下与reduce一起工作的方法,并且不假设你在reduce函数中有L可用:

from operator import truediv

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

def sum_and_count(x, y):
    try:
        return (x[0] + y, x[1] + 1)
    except TypeError:
        return (x + y, 2)

truediv(*reduce(sum_and_count, L))

# prints 
20.11111111111111