![](/img/trans.png)
[英]Looking for a more efficient/pythonic way to sum tuples in a list, and compute an average
[英]Fastest way to compute average of a list
我想找到计算 python list
平均值的最快方法。 我有数百万个list
存储在dictionary
中,因此我正在寻找性能方面最有效的方法。
参考这个问题,如果l
是浮点数列表,我有
numpy.mean(l)
sum(l) / float(len(l))
reduce(lambda x, y: x + y, l) / len(l)
哪种方式最快?
正如@DeepSpace 所建议的那样,您应该尝试自己回答这个问题。 在使用numpy.mean
之前,您还可以考虑将列表转换为数组。 将%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.arrayIn [5]: %timeit numpy.mean(l)
32.5 µs ± 2.82 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
numpy.mean
转换为 np.arrayIn [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)
sum(l) / float(len(l))
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)
sum(l) / len(l)
In [5]: %timeit sum(l) / len(l)
623 ns ± 27.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
reduce
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)
从最慢到最快:
numpy.mean(l)
不转换为数组np.array
后numpy.mean(a)
reduce(lambda x, y: x + y, l) / len(l)
sum(l) / float(len(l))
,这适用于 Python 2 和 3sum(l) / len(l)
# 对于 Python 3,你不需要强制转换(使用float
)下午好,我刚刚对列表中的 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()
与往常一样,我确信有更好的方法可以做到这一点,但这可以解决问题。 这是一个小列表:看看你在大列表中找到了什么会很有趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.