Python 中的bisect


Python 中的bisect用於操作排序的數組,比如你可以在向一個數組插入數據的同時進行排序。下面的代碼演示了如何進行操作:

import bisect
import random
random.seed(1)
print('New pos contents')
print('-----------------')
l=[]

for i in range(1,15):
    r=random.randint(1,100)
    position=bisect.bisect(l,r)
    bisect.insort(l,r)
    print '%3d %3d'%(r,position),l

輸出結果為:

New pos contents
-----------------
 14   0 [14]
 85   1 [14, 85]
 77   1 [14, 77, 85]
 26   1 [14, 26, 77, 85]
 50   2 [14, 26, 50, 77, 85]
 45   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, 50, 66, 77, 79, 85]
 84   9 [3, 10, 14, 26, 45, 50, 66, 77, 79, 84, 85]
 44   4 [3, 10, 14, 26, 44, 45, 50, 66, 77, 79, 84, 85]
 77   9 [3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]
  1   0 [1, 3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]


可以看到,在插入這些隨機數的時候數組同時進行了排序。不過其中有一些重復的元素,比如上面的77,77。你可以對這些重復元素的順序進行設置,如果希望重復的元素出現在與他相同的元素左邊就是用bisect_left,否則就是用bisect_right,相應的使用insort_left和insort_right。比如下面的代碼,我們可以看到出現重復的元素索引變化:

 

import bisect
import random
random.seed(1)
print('New pos contents')
print('-----------------')
l=[]

for i in range(1,15):
    r=random.randint(1,100)
    position=bisect.bisect_left(l,r)
    bisect.insort_left(l,r)
    print '%3d %3d'%(r,position),l

輸出結果為:

New pos contents
-----------------
 14   0 [14]
 85   1 [14, 85]
 77   1 [14, 77, 85]
 26   1 [14, 26, 77, 85]
 50   2 [14, 26, 50, 77, 85]
 45   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, 50, 66, 77, 79, 85]
 84   9 [3, 10, 14, 26, 45, 50, 66, 77, 79, 84, 85]
 44   4 [3, 10, 14, 26, 44, 45, 50, 66, 77, 79, 84, 85]
 77   8 [3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]
  1   0 [1, 3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]

此函數bisect.bisect(list,key) ,猶如java里的TreeMap的tailMap(fromkey)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM