Python 计算列表平均值的最快方法

Python 计算列表平均值的最快方法,python,python-2.7,Python,Python 2.7,我想找到计算pythonlists平均值的最快方法。我有数以百万计的列表存储在字典中,因此我正在寻找性能方面最有效的方法 指, 如果l是一个浮点数列表,则 numpy.平均值(l) sum(l)/float(len(l)) reduce(λx,y:x+y,l)/len(l) 哪条路最快?下午好, 我只是用一个列表中的10个随机浮点数做了一个测试,然后运行了一个时间测试,发现numpy是最快的 #!/usr/bin/python import numpy as np from functoo

我想找到计算python
list
s平均值的最快方法。我有数以百万计的
列表
存储在
字典
中,因此我正在寻找性能方面最有效的方法

指, 如果
l
是一个浮点数列表,则

  • numpy.平均值(l)
  • sum(l)/float(len(l))
  • reduce(λx,y:x+y,l)/len(l)
哪条路最快?

下午好, 我只是用一个列表中的10个随机浮点数做了一个测试,然后运行了一个时间测试,发现numpy是最快的

#!/usr/bin/python

import numpy as np
from functools import reduce
import time

l = [0.1, 2.3, 23.345, 0.9012, .002815, 8.2, 13.9, 0.4, 3.02, 10.1]

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

def test2():
    return sum(l) / float(len(l))

def test3():
    return reduce(lambda x, y: x + y, l) / len(l)

def timed():
    start = time.time()
    test1()
    print('{} seconds'.format(time.time() - start))
    start = time.time()
    test2()
    print('{} seconds'.format(time.time() - start))
    start = time.time()
    test3()
    print('{} seconds'.format(time.time() - start))

timed()
像往常一样,我确信有更好的方法来做到这一点,但这确实奏效了。
这是一个小列表:看看你在大列表中发现了什么会很有趣。

正如@DeepSpace所建议的,你应该试着回答这个问题。您也可以考虑在使用<代码> NoPy.Medie<代码>之前将列表转换为数组。将
%timeit
ipython
一起使用,如下所示:

In [1]: import random
In [2]: import numpy
In [3]: from functools import reduce
In [4]: l = random.sample(range(0, 100), 50) # generates a random list of 50 elements
numpy.mean
不转换为np.array
numpy.mean
转换为np.array
sum(l)/float(len(l))
sum(l)/len(l)
reduce
从最慢到最快:

  • numpy.mean(l)
    不转换为数组
  • numpy.mean(a)
    将列表转换为
    np.array后
  • reduce(λx,y:x+y,l)/len(l)
  • sum(l)/float(len(l))
    ,这适用于Python 2和Python 3
  • sum(l)/len(l)
    #对于Python 3,您不需要强制转换(使用
    float

  • <代码>哪种方式最快?< /代码>为什么不测试并让我们知道?公平地说,如果你考虑使用<代码> NoMPy < /C> >,你可能已经将这些值存储在一个数组中,而不是一个列表中。使用
    a=numpy.array(l)
    numpy.mean(a)
    的速度是
    numpy.mean(l)
    的两倍。我也没有试过更长的时间来观察每一个变量的大小。@chepner,我同意你的看法。我将把它添加到我的答案中。@chepner,我更新了我的答案,我同意你的说法,在转换为数组后,它的速度是不转换的两倍。
    In [5]: %timeit numpy.mean(l)
    32.5 µs ± 2.82 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    
    In [5]: a = numpy.array(a)
    In [6]: %timeit numpy.mean(a)
    17.6 µs ± 205 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
    In [5]: %timeit sum(l) / float(len(l)) # not required casting (float) in Python 3
    774 ns ± 20.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    In [5]: %timeit sum(l) / len(l)
    623 ns ± 27.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    In [6]: reduce(lambda x, y: x + y, l) / len(l)
    5.92 µs ± 514 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)