《流畅的python》:bisect来管理已排序的序列

bisect模块提供的功能:

一共包含四个函数

insort_right(a, x, lo=0, hi=None)
bisect_right(a, x, lo=0, hi=None)
insort_left(a, x, lo=0, hi=None)
bisect_left(a, x, lo=0, hi=None)

insort_right函数:a是升序排列的,将x插入a后,仍然保持a升序排列;如果x已经存在于a中,则将x插入已经存在的值的右边

insort_left函数:a是升序排列的,将x插入a后,仍然保持a升序排列;如果x已经存在于a中,则将x插入已经存在的值的左边

bisect_right函数:a是升序排列的,返回x插入的索引值,满足插入x后,a仍是升序排列;当x已经存在于a中,返回的是已经存在的x右边的索引值

bisect_left函数:a是升序排列的,返回x插入的索引值,满足插入x后,a仍是升序排列;当x已经存在于a中,返回的是已经存在的x左边的索引值

其中可选参数lo默认为0,hi默认为列表长度值,限定搜索的范围

上述情况的演示代码:

import bisect

haystack = [1,5,6,8,12,15,20,21,23,23,26,29,30]
needles = [0,1,2,5,8,10,22,23,29,30,31]

for needle in needles:
    positon = bisect.bisect_left(haystack,needle)
    print("元素{}插入的位置为{}".format(needle,positon))
    bisect.insort_left(haystack,needle)
    print("插入后的列表为{}".format(haystack))

for needle in needles:
    positon = bisect.bisect(haystack,needle)
    print("元素{}插入的位置为{}".format(needle,positon))
    bisect.insort(haystack,needle)
    print("插入后的列表为{}".format(haystack))

for needle in needles:
    positon = bisect.bisect_left(haystack,needle,lo=3,hi=5)
    print("元素{}插入的位置为{}".format(needle,positon))
    bisect.insort_left(haystack,needle,lo=3,hi=5)
    print("插入后的列表为{}".format(haystack))

 

原文地址:https://www.cnblogs.com/canghai1024/p/13889392.html