本文實例講述了python中bisect模塊用法,分享給大家供大家參考。
具體方法分析如下:
這個模塊只有幾個函數,一旦決定使用二分搜索時,立馬要想到使用這個模塊。
示例代碼如下:
import bisectL = [1,3,3,6,8,12,15]x = 3x_insert_point = bisect.bisect_left(L,x)#在L中查找x,x存在時返回x左側的位置,x不存在返回應該插入的位置..這是3存在于列表中,返回左側位置1print x_insert_pointx_insert_point = bisect.bisect_right(L,x)#在L中查找x,x存在時返回x右側的位置,x不存在返回應該插入的位置..這是3存在于列表中,返回右側位置3print x_insert_pointx_insort_left = bisect.insort_left(L,x)#將x插入到列表L中,x存在時插入在左側print Lx_insort_rigth = bisect.insort_right(L,x)#將x插入到列表L中,x存在時插入在右側print L
本例測試環境為Python2.7.6
示例運行結果如下:
13[1, 3, 3, 3, 6, 8, 12, 15][1, 3, 3, 3, 3, 6, 8, 12, 15]
實際使用中bisect.insort_left與 bisect.insort_right 差別不大,作用基本相同。
希望本文所述對大家Python程序設計的學習有所幫助。
新聞熱點
疑難解答