python笔记之bisect模块

python笔记之bisect模块

当你决定使用二分搜索时,这个模块会给你带来很大的帮助。

例子

import bisect
L = [1,3,3,6,8,12,15]
x = 3

#在L中查找x,x存在时返回x左侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回左侧位置1
x_insert_point = bisect.bisect_left(L,x)
print x_insert_point #1

#在L中查找x,x存在时返回x右侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回右侧位置3
x_insert_point = bisect.bisect_right(L,x)
print x_insert_point #3

#将x插入到列表L中,x存在时插入在左侧
x_insort_left = bisect.insort_left(L,x)
print L #[1,3,3,3,6,8,12,15]

#将x插入到列表L中,x存在时插入在右侧
x_insort_rigth = bisect.insort_right(L,x)
print L #[1, 3, 3, 3, 3, 6, 8, 12, 15]

#实际使用中bisect.insort_left与 bisect.insort_right 差别不大,作用基本相同
原文地址:https://www.cnblogs.com/bergus/p/4811314.html