本文實例講述了python中bisect模塊用法,分享給大家供大家參考。
具體方法分析如下:
這個模塊只有幾個函數(shù),一旦決定使用二分搜索時,立馬要想到使用這個模塊。
示例代碼如下:
import bisectL = [1,3,3,6,8,12,15]x = 3x_insert_point = bisect.bisect_left(L,x)#在L中查找x,x存在時返回x左側(cè)的位置,x不存在返回應(yīng)該插入的位置..這是3存在于列表中,返回左側(cè)位置1print x_insert_pointx_insert_point = bisect.bisect_right(L,x)#在L中查找x,x存在時返回x右側(cè)的位置,x不存在返回應(yīng)該插入的位置..這是3存在于列表中,返回右側(cè)位置3print x_insert_pointx_insort_left = bisect.insort_left(L,x)#將x插入到列表L中,x存在時插入在左側(cè)print Lx_insort_rigth = bisect.insort_right(L,x)#將x插入到列表L中,x存在時插入在右側(cè)print L
本例測試環(huán)境為Python2.7.6
示例運行結(jié)果如下:
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程序設(shè)計的學(xué)習(xí)有所幫助。
新聞熱點
疑難解答
圖片精選