bisect模块包含两个函数,bisect和insert,两个函数都利用二分查找算法在有序序列中查找或插入元素
用bisect来搜索
bisect(ordered_sequence, needle)
ordered_sequence:必须是一个有序的序列
needle:指定序列中需要搜索的位置数
ordered_sequence和needle只是举栗子的位置参数,无需关注
栗子:
gg = [33, 99, 77, 70, 89, 90, 100]
print(bisect.bisect(gg, 100))
运行后的结果如下
7
从运行的结果可以看出,查找的是元素插入的索引位置并返回出来,这点要注意...
bisect函数其实是bisect_right函数的别名,就是进行了赋值操作,图片如下:
再看下bisect_right函数的源码:
def insort_right(a, x, lo=0, hi=None):
"""Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the right of the rightmost x.
Optional args lo (defa