前言在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 ;map 和列表推導
1 #File: map-1.py
2 #coding=utf-8 3 import time 4 5 list = [i for i in range(1,500000)]
|
結論其實二者差異不太大,能夠歸結爲編碼風格問題,可是我我的比較喜歡pythonic的列表推導,恰好它的效率也高點! utf-8 |