python bisect_python bisect模块

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

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

先看看模块的结构:

7e93203d86d28e7db15b3b774c518220.png

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

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

d4393365e6a6c4e4d4fe7bff2eb80b81.png

先看看 insort  函数:

3ccde160a1724b3539def8892b87145f.png

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

再看看 bisect  函数:

3d36ca221c28bc270cec310ce5b27239.png

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

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

4b805a63680144953b9f7ae7c3176f63.png

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

2ec790453761d9bf0a8e5edac0f79a09.png

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

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

这个模块只有几个函数,

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

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]

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

示例

importbisect

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))defdemo(bisect_fn):for needle inreversed(NEEDLES):

position=bisect_fn(HAYSTACK, needle)print(ROW_FMT.format(needle, position))#bisect_fn = bisect.bisect

bisect_fn =bisect.bisect_leftprint('DEMO:', bisect_fn.__name__)print('haystack ->', ' '.join('%2d' % n for n inHAYSTACK))

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值