亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算列表平均值的最快方法

計算列表平均值的最快方法

臨摹微笑 2022-06-02 10:10:09
我想找到計算 python 平均值的最快方法list。我有數百萬個lists 存儲在 a 中dictionary,因此我正在尋找性能方面最有效的方法。參考這個問題,如果l是浮點數列表,我有numpy.mean(l)sum(l) / float(len(l))reduce(lambda x, y: x + y, l) / len(l)哪種方式最快?
查看完整描述

2 回答

?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

正如@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.array

In [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.array

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)

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)

從最慢到最快:

  1. numpy.mean(l)無需轉換為數組

  2. numpy.mean(a)將列表轉換為np.array

  3. reduce(lambda x, y: x + y, l) / len(l)

  4. sum(l) / float(len(l)), 這適用于 Python 2 和 3

  5. sum(l) / len(l)# 對于 Python 3,你不需要強制轉換(使用float


查看完整回答
反對 回復 2022-06-02
?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

下午好,我剛剛對列表中的 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()

與往常一樣,我確信有更好的方法可以做到這一點,但這可以解決問題。這是一個小列表:看看你在大列表中找到了什么會很有趣。


查看完整回答
反對 回復 2022-06-02
  • 2 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號