python bisect模块

转自: https://www.cnblogs.com/skydesign/archive/2011/09/02/2163592.html

如果在插入新元素的同时还想保持有序序列的顺序, 那么需要用到 bisect.insortbisect.bisect 的作用则是快速查找。

 今天同事说到了一个python的排序模块bisect,觉得挺有趣的,跟大家分享分享。

       先看看模块的结构:

      

       前面五个属性大家感兴趣可以打出来看看数值,这里就不介绍了。

       先说明的是,使用这个模块的函数前先确保操作的列表是已排序的。

      

       先看看 insort  函数:

       

       其插入的结果是不会影响原有的排序。

       再看看 bisect  函数:

       

       其目的在于查找该数值将会插入的位置并返回,而不会插入。

       接着看 bisect_left 和 bisect_right 函数,该函数用入处理将会插入重复数值的情况,返回将会插入的位置:

       

       其对应的插入函数是 insort_left  和 insort_right :

       

       可见,单纯看其结果的话,两个函数的操作结果是一样的,其实插入的位置不同而已。

#####################

这个模块只有几个函数,

一旦决定使用二分搜索时,立马要想到使用这个模块 

import bisect

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

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

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

print x_insert_point

x_insort_left = bisect.insort_left(L,x) #将x插入到列表L中,x存在时插入在左侧
print L

x_insort_rigth = bisect.insort_right(L,x) #将x插入到列表L中,x存在时插入在右侧    

print L

结果:
1
3
[1, 3, 3, 3, 6, 8, 12, 15]
[1, 3, 3, 3, 3, 6, 8, 12, 15]

#####################

示例

import bisect
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
ROW_FMT = '{0:2d} @ {1:2d}'
print(len(HAYSTACK))


def demo(bisect_fn):
    for needle in reversed(NEEDLES):
        position = bisect_fn(HAYSTACK, needle)
        print(ROW_FMT.format(needle, position))

#bisect_fn = bisect.bisect
bisect_fn = bisect.bisect_left
print('DEMO:', bisect_fn.__name__)
print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK))
demo(bisect_fn)

###################

14
DEMO: bisect_left
haystack -> 1 4 5 6 8 12 15 20 21 23 23 26 29 30
31 @ 14
30 @ 13
29 @ 12
23 @ 9
22 @ 9
10 @ 5
8 @ 4
5 @ 2
2 @ 1
1 @ 0
0 @ 0

 

posted @ 2018-11-08 09:51  JAYWX  阅读(525)  评论(0编辑  收藏  举报