bisect –維護有序列表
目的:不需要每次調用sort的方式維護有序列表。
bisect模組實作了一個演算法用於插入元素到有序列表。在某些情況下,這比反覆排序清單或建構一個大的清單再排序的效率更高。 Bisect是二分法的意思,這裡使用二分法來排序,bisect的原始碼是二分法排序的樣板。這個模組的程式碼不到100行。
插入
import bisect import random # Use aconstant seed to ensure that # the samepseudo-random numbers # are usedeach time the loop is run. random.seed(1) print'New Pos Contents' print'--- --- --------' # Generaterandom numbers and # insert theminto a list in sorted # order. l = [] for i inrange(1, 15): #产生1-100的随机数 r = random.randint(1, 100) position = bisect.bisect(l, r) bisect.insort(l, r) print'%3d %3d' % (r, position), l
執行結果:
#./bisect_example.py
New Pos Contents
--- --- --------
14 1
14, 85]77 1[14, 77, 85]26 1[14, 26, 77, 85]50 2[14, 2[14, 26, 45, 50, 77, 85]66 4[14, 26, 45, 50, 66, 77, 85]79 6[14, 26, 45, 50, 66, 77, 79, 85] 10 0[10, 14, 26, 45, 50, 66, 77, 79, 85] 3 0[3, 10, 14, 26, 45,757,75, 57,75, 26095, 57,757, 57,757, 57,75, 57,757, 57,757, 57,757, 57,757, 57,753, 57,75, 57,753, 57,75, 57,753, 57,75, 57,75, 57,757, 57,757, 57,575] 84 9[3, 10, 14, 26, 45, 50, 66, 77, 79, 84, 85]44 4[3, 10, 14, 26, 45, 4 4[3, 10, 14, 26, 49, 4 84, 85]77 9[3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85] 14, 3 44, 45, 50, 66, 77, 77, 79, 84, 85]Bisect模組所提供的函數有:
bisect.bisect_left(a,x, loft(a,x, lo, bis) ) :
>>> data =[('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)] >>> data.sort(key=lambdar: r[1]) >>> keys =[r[1] for r in data] #precomputed list of keys >>> data[bisect_left(keys,0)] ('black', 0) >>> data[bisect_left(keys,1)] ('blue', 1) >>> data[bisect_left(keys,5)] ('red', 5) >>> data[bisect_left(keys,8)] ('yellow', 8)