Python 查找列表的平均值

Python 查找列表的平均值,python,list,lambda,average,reduce,Python,List,Lambda,Average,Reduce,我必须找到Python中列表的平均值。这是到目前为止我的代码 l = [15, 18, 2, 36, 12, 78, 5, 6, 9] print reduce(lambda x, y: x + y, l) 我得到了它,因此它将列表中的值相加,但我不知道如何将其划分为多个值?在Python 3.4+上,您可以使用 在较早版本的Python上,您可以执行以下操作 sum(l) / len(l) 在Python2上,需要将len转换为浮点以获得浮点除法 sum(l) / float(len(l)

我必须找到Python中列表的平均值。这是到目前为止我的代码

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)

我得到了它,因此它将列表中的值相加,但我不知道如何将其划分为多个值?

在Python 3.4+上,您可以使用

在较早版本的Python上,您可以执行以下操作

sum(l) / len(l)
在Python2上,需要将
len
转换为浮点以获得浮点除法

sum(l) / float(len(l))

无需使用
reduce
。它的速度要慢得多,而且是在Python3中。

当Python有一个完美的cromultent
sum()函数时,为什么要使用
reduce()

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(l) / len(l)
print sum(l) / float(len(l))
(强制Python进行浮点除法需要
float()

或者像以前贴的那样

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

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

为了使用
reduce
来计算运行平均值,你需要跟踪到目前为止看到的元素总数和总数。由于这在列表中不是一个微不足道的元素,您还必须传递一个额外的参数来折叠

sum(l) / float(len(l))
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> running_average = reduce(lambda aggr, elem: (aggr[0] + elem, aggr[1]+1), l, (0.0,0))
>>> running_average[0]
(181.0, 9)
>>> running_average[0]/running_average[1]
20.111111111111111
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
您可以使用:

已经完成了一个模块。它有一个函数来计算调用的平均值。您提供的列表示例如下:

from statistics import mean
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
mean(l)

您可以向总和中添加0.0,而不是强制转换为浮点:

def avg(l):
    return sum(l, 0.0) / len(l)

在一个大学的问题中,我有一个类似的问题要解决。而不是我编码的内置函数:

def list_mean(n):

    summing = float(sum(n))
    count = float(len(n))
    if n == []:
        return False
    return float(summing/count)

比平常长得多,但对于初学者来说,这是一个相当具有挑战性的问题。

这两种方法都可以为您提供接近整数或至少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

@安德鲁·克拉克的说法是正确的。

我尝试使用上述选项,但没有成功。 试试这个:

从统计导入平均值
n=[11,13,15,17,19]
打印(n)
打印(平均值(n))

在Python3.5上工作时,结合上述两个答案,我提出了以下与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

作为初学者,我刚刚编写了以下代码:

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)

我只想添加另一种方法

import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)
假设

x = [
    [-5.01,-5.43,1.08,0.86,-2.67,4.94,-2.51,-2.25,5.56,1.03],
    [-8.12,-3.48,-5.52,-3.78,0.63,3.29,2.09,-2.13,2.86,-3.33],
    [-3.68,-3.54,1.66,-4.11,7.39,2.08,-2.59,-6.94,-2.26,4.33]
]
您可以注意到,
x
的维度为3*10,如果您需要为每一行输入
平均值

theMean = np.mean(x1,axis=1)

不要忘记将numpy作为np导入

如果您使用的是python>=3.4,那么就有一个统计库

你可以用这种卑鄙的方法。假设您有一个要查找的数字列表,其意思是:-

list = [11, 13, 12, 15, 17]
import statistics as s
s.mean(list)
它还有其他方法,如标准差分法、方差法、模式法、调和平均法、中值法等,这些方法非常有用。

如果你想得到的不仅仅是平均值(又称平均值),你可以查看scipy统计数据
或者使用
pandas
系列。平均值
方法:

pd.Series(sequence).mean()
演示:

>>> import pandas as pd
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> pd.Series(l).mean()
20.11111111111111
>>> 
从文档中:

系列。平均值(轴=无,skipna=无,级别=无,仅数值=无,**kwargs)

以下是这方面的文件:

以及整个文件:

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

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

试着简单一点。

就效率和速度而言,以下是我在测试其他答案时得到的结果:

# test mean caculation

import timeit
import statistics
import numpy as np
from functools import reduce
import pandas as pd

LIST_RANGE = 10000000000
NUMBERS_OF_TIMES_TO_TEST = 10000

l = list(range(10))

def mean1():
    return statistics.mean(l)


def mean2():
    return sum(l) / len(l)


def mean3():
    return np.mean(l)


def mean4():
    return np.array(l).mean()


def mean5():
    return reduce(lambda x, y: x + y / float(len(l)), l, 0)

def mean6():
    return pd.Series(l).mean()



for func in [mean1, mean2, mean3, mean4, mean5, mean6]:
    print(f"{func.__name__} took: ",  timeit.timeit(stmt=func, number=NUMBERS_OF_TIMES_TO_TEST))
结果是:

mean1 took:  0.17030245899968577
mean2 took:  0.002183011999932205
mean3 took:  0.09744236000005913
mean4 took:  0.07070840100004716
mean5 took:  0.022754742999950395
mean6 took:  1.6689282460001778
所以很明显,获胜者是:
sum(l)/len(l)

numpy。意思是如果你有能力安装numpy
sum(l)/float(len(l))
。处理调用方代码中的空列表,如
if not L:…
@mitch:这不是你是否能负担得起安装numpy的问题。numpy本身就是一个完整的词。关键是你是否真的需要numpy。安装numpy(一个16mb的C扩展,用于均值计算)对于不使用它的人来说是非常不切实际的。如果使用Python3,我们可以使用statistic模块通过“from statistic import mean”或在Python2.7或更低版本上,而不是安装整个numpy包用于avg/mean,统计模块可以从src:doc:下载并直接使用。这很完美!对不起,这个愚蠢的问题,但我真的到处找了!非常感谢你!正如我所说的,我是新手,我在想我必须用一个循环或其他东西来计算其中的数字量,我没有意识到我可以只使用长度。这是我用python做的第一件事。@CarlaDessi:你在用什么教程?我看过的所有教程都详细介绍了这一点。很明显,你已经找到了一个没有很好涵盖这一点的教程。你用什么教程来学习Python?如果总和是一个不适合int/float的大数怎么办?@FooBarUser那么你应该计算k=1.0/len(l),然后reduce:reduce(lambda x,y:x+y*k,l)有趣,但这不是他想要的。我知道这只是为了好玩,但返回0表示空列表可能不是最好的选择do@JohanLundberg-您可以将0替换为False,作为
reduce()
的最后一个参数,这将为空列表提供False,否则,平均值与以前一样。@AndrewClark为什么强制
len
浮动
?效率低下。它在添加元素之前将所有元素转换为浮点。只转换长度更快。对于我们这些新手来说,
float()
在Python3.Good上是不必要的。其他所有答案都没有注意到空列表危险!返回
False
(相当于整数
0
)几乎是处理此错误最糟糕的方法。最好抓住零分错误并提出更好的建议(也许是
ValueError
)。@那么
ValueError
pd.Series(sequence).mean()
>>> import pandas as pd
>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> pd.Series(l).mean()
20.11111111111111
>>> 
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(sum(l)//len(l))
# test mean caculation

import timeit
import statistics
import numpy as np
from functools import reduce
import pandas as pd

LIST_RANGE = 10000000000
NUMBERS_OF_TIMES_TO_TEST = 10000

l = list(range(10))

def mean1():
    return statistics.mean(l)


def mean2():
    return sum(l) / len(l)


def mean3():
    return np.mean(l)


def mean4():
    return np.array(l).mean()


def mean5():
    return reduce(lambda x, y: x + y / float(len(l)), l, 0)

def mean6():
    return pd.Series(l).mean()



for func in [mean1, mean2, mean3, mean4, mean5, mean6]:
    print(f"{func.__name__} took: ",  timeit.timeit(stmt=func, number=NUMBERS_OF_TIMES_TO_TEST))
mean1 took:  0.17030245899968577
mean2 took:  0.002183011999932205
mean3 took:  0.09744236000005913
mean4 took:  0.07070840100004716
mean5 took:  0.022754742999950395
mean6 took:  1.6689282460001778