美文网首页
python的filter

python的filter

作者: 代码小不全 | 来源:发表于2018-11-05 12:54 被阅读0次

filter作为python的内置高阶函数,常用来过滤列表(或其他序列),最近遇到一个问题,对比了一下filter与自定义实现过滤方法的比较,有点新发现,记录一下。

  • filter很慢。慢到什么程度呢?还没有初学者最爱写的for循环快。
  • 不过for循环的两种不同写法,差异也挺大,下标索引完败。
  • 完成同样的事,列表推导式是最快的,不过也没有比for快多少。
  • 验证情况如下。
  • 环境:win10 + python 3.7.1
import time


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 = []
    for x in listSrc:
        if x % 3 == 0:
            res.append( x )
    return res


def forC( listSrc ):

    res = []
    for i in range( len(listSrc) ):
        if listSrc[i] % 3 == 0:
            res.append( listSrc[i] )
    return res
        
def filterF( listSrc ):
    return list( filter( lambda x: x%3==0, listSrc ) )

def listF( listSrc ):
    return [ x for x in listSrc if x%3==0 ]


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

if __name__ == '__main__':
    
    testFun( forA )
    testFun( forC )
    testFun( filterF )
    testFun( listF )

时间消耗:

  • forA cost seconds= 8.46875
  • forC cost seconds= 13.21875
  • filterF cost seconds= 15.14062
  • listF cost seconds= 7.79688

不知道另外几个高阶函数reduce、map怎么样?改天试试。
先大胆推测一下:估计跟filter类似

相关文章

网友评论

      本文标题:python的filter

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