我想找到计算 python 平均值的最快方法list。我list在 a 中存储了数百万个 s dictionary,因此我正在寻找性能方面最有效的方法。
参考这个问题,如果l是浮点数列表,我有
numpy.mean(l)sum(l) / float(len(l))reduce(lambda x, y: x + y, l) / len(l)哪种方式最快?
lmi*_*asf 10
正如@DeepSpace 所建议的,你应该尝试自己回答这个问题。您还可以考虑在使用之前将列表转换为数组numpy.mean。使用%timeit如下ipython:
In [1]: import random\nIn [2]: import numpy\nIn [3]: from functools import reduce\nIn [4]: l = random.sample(range(0, 100), 50) # generates a random list of 50 elements\nRun Code Online (Sandbox Code Playgroud)\n\nnumpy.mean无需转换为 np.arrayIn [5]: %timeit numpy.mean(l)\n32.5 \xc2\xb5s \xc2\xb1 2.82 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\nnumpy.mean转换为 np.arrayIn [5]: a = numpy.array(a)\nIn [6]: %timeit numpy.mean(a)\n17.6 \xc2\xb5s \xc2\xb1 205 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\nsum(l) / float(len(l))In [5]: %timeit sum(l) / float(len(l)) # not required casting (float) in Python 3\n774 ns \xc2\xb1 20.4 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\nsum(l) / len(l)In [5]: %timeit sum(l) / len(l)\n623 ns \xc2\xb1 27.4 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\nreduceIn [6]: reduce(lambda x, y: x + y, l) / len(l)\n5.92 \xc2\xb5s \xc2\xb1 514 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\n从最慢到最快:
\n\nnumpy.mean(l)不转换为数组numpy.mean(a)将列表转换为之后np.arrayreduce(lambda x, y: x + y, l) / len(l)sum(l) / float(len(l)),这适用于 Python 2 和 3sum(l) / len(l)# 对于Python 3,你不需要强制转换(使用float)| 归档时间: |
|
| 查看次数: |
7810 次 |
| 最近记录: |