python列表推導 和 內置函數map,filter 效率對比(轉)

前言

在python中的列表操做主要有兩種, 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


結果: spa

;

map 和列表推導

1 #File: map-1.py
2 #coding=utf-8
3 import time
4
5 list = [i for i in range(1,500000)]

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的列表推導,恰好它的效率也高點! utf-8

相關文章
相關標籤/搜索