美文网首页
python的reduce和map

python的reduce和map

作者: 代码小不全 | 来源:发表于2018-11-14 23:39 被阅读0次

承上:python的filter
大胆假设,小心求证,结果如下。

import time
from functools import reduce


def costTime( fun ):
    def w( *args, **kwargs ):
        
        name = getattr( *args, '__name__' )

        fb = time.process_time()
        ret = fun( *args, **kwargs )
        fe = time.process_time()
    
        print( name, 'cost seconds=', round( fe - fb, 5 ) )

        return ret

    return w


listA = [ 1,2,3,4,5,6,7,8,9,10 ] * 10


def forA( listSrc ):

    res = 0
    for x in listSrc:
        res += 2 * x 
    return res


def forC( listSrc ):

    res = 0
    for i in range( len(listSrc) ):
        res += 2 * listSrc[i]
    return res

     
def reduceF( listSrc ):
    return reduce( lambda x,y : x+2*y, listSrc, 0 )



def forMap( listSrc ):
    res = []
    for x in listSrc:
        res.append( x*x )
    return res

def listMap( listSrc ):
    return [ x*x for x in listSrc ]

def mapF( listSrc ):
    return list( map( lambda x:x*x, listSrc ) )


@costTime
def testFun( fun ):
    i = 0
    while i<1000000:
        fun( listA )
        i = i+1
    

if __name__ == '__main__':
    
    testFun( forA )
    testFun( forC )
    testFun( reduceF )

    testFun( forMap )
    testFun( listMap )
    testFun( mapF )

时间消耗:

  • reduce对比

    • forA cost seconds= 6.78125
    • forC cost seconds= 9.71875
    • reduceF cost seconds= 14.45312
  • map对比

    • forMap cost seconds= 10.76562
    • listMap cost seconds= 5.53125
    • mapF cost seconds= 12.90625

验证的情况基本符合猜想。
简单总结一下:

  • 列表推导式最快,写起来也简单。能用列表推导式写就不要用filter、map了。不过map和for循环的差距,没有filter和for循环的那么大。
  • 对于reduce,无法构造同等作用的列表推导式。for循环比reduce几乎快一半,就是写起来稍微啰嗦一点。
  • for循环中,尽量别使用下标模式。

验证环境:win10 + python 3.7.1

相关文章

网友评论

      本文标题:python的reduce和map

      本文链接:https://www.haomeiwen.com/subject/dtkjxqtx.html