python列表推导 和 内置函数map,filter 效率对比


前言
在python中的列表操作主要有两种,
一种类似于lisp的函数编程方法:filter( function,list) , map( function, list)
另一种特别pythonic——列表推导 [ i for i in list ]
现在就两种方法进行对比,看看哪种效率高
________________________________________
filter 和 列表推导
file: filter-1.py
 1 #coding=utf-8
 2 import time
 3
 4 list = [i for i in range(1,50000)]
 5 start = time.time()
 6 for i in range(0,1000):   
 7     list1 = filter(lambda i: i%2==0, list) # filter
 8 print time.time() - start
 9 #print list1
10    

file: filter-2.py
 1 #coding=utf-8
 2 import time
 3
 4 list = [i for i in range(1,50000)]
 5 start = time.time()
 6 for i in range(0,1000):   
 7     list1 = [i for i in list if i % 2 == 0]  # 列表推导
 8 print time.time() - start
 9 #print list1
10    


结果:

  \


 

map和列表推导
 
 1 #File: map-1.py
 2 #coding=utf-8
 3 import time
 4
 5 list = [i for i in range(1,50000)]
 6 start = time.time()
 7 for i in range(0,1000):   
 8     list1 = map(lambda i: i*2, list)
 9 print time.time() - start
10 #print list1
11    

 
 
#File: map-2.py
#coding=utf-8
import time

list = [i for i in range(1,50000)]
start = time.time()
for i in range(0,1000):   
    list1 = [ i*2 for i in list ]
print time.time() - start
#print list1
   

 
结果:

  \


 

结论
其实两者差别不太大,可以归结为编码风格问题,但是我个人比较喜欢pythonic的列表推导,刚好它的效率也高点!^_^
 

 

摘自   hate感冒 

相关内容

    暂无相关文章

评论关闭