本文實例講述了Python中map和列表推導效率比較。分享給大家供大家參考。具體分析如下:
直接來測試代碼吧:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#!/usr/bin/env python # -*- coding: utf-8 -*- # list comprehension and map import time def test(f, name): st = time.time() f() print '%s %ss' % (name, time.time() - st) TIMES = 1000 ARR = range ( 10000 ) def tmap(): i = 0 while (i<TIMES): map ( lambda x:x, ARR) i = i + 1 def tlst(): i = 0 while (i<TIMES): [x for x in ARR] i = i + 1 test(tmap, "map" ) test(tlst, "lst" ) |
在我電腦上的測試結果:
1
2
|
map 1.06299996376s lst 0.296000003815s |
很明顯列表推導比map操作會快很多,都三倍速度了
希望本文所述對大家的Python程序設計有所幫助。