python 内置bisect(对分) 模块 排序: 有序序列的查找和插入

直接上码

>>> import bisect
>>> list1 = [1,2,3,4, 6, 7, 10]  // 这是一个有序序列
>>> bisect.bisect(list1, 5)  // 返回5应该在list1中的索引
4
>>> list1  // 但list1没变
[1, 2, 3, 4, 6, 7, 10]
>>> bisect.insort(list1, 5)   // 这里是insort, 不是insert, 
>>> list1
[1, 2, 3, 4, 5, 6, 7, 10]    // list1 结果变了
>>> list1.insert(0, 8)     // list的insert操作,无特殊意义
>>> list1
[8, 1, 2, 3, 4, 5, 6, 7, 10]
>>> list1.insert(8, 8)
>>> list1
[8, 1, 2, 3, 4, 5, 6, 7, 8, 10]
>>> 

bisect.insort 可以插入有序序列中应当出现的位置,不需要指定位置,
list.insert可以插入list中任何一个位置,list可以是无序的,

代码详解一哈

In [1]: import bisect

In [2]: dir(bisect)
Out[2]:
['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'bisect',
 'bisect_left',
 'bisect_right',
 'insort',
 'insort_left',
 'insort_right']

In [3]: s1 = ['a', 'b', 'h']


In [4]: bisect.bisect(s1, 'a')
Out[4]: 1
# 意思是: 将元素'a'插入到s1序列中, 返回应当插入位置的索引
In [5]: bisect.bisect_left(s1, 'h')
Out[5]: 2
# 意思是: 将元素'h'插入到s1序列中, 返回左侧插入位置的索引
In [6]: bisect.bisect_right(s1, 'h')
Out[6]: 3
# 意思是: 将元素'h'插入到s1序列中, 返回右则插入位置的索引

In [7]: bisect.insort(s1, 'h')
# 意思是: 将元素'h'插入到s1序列中
In [8]: bisect.insort(s1, 'z')

In [9]: s1
Out[9]: ['a', 'b', 'h', 'h', 'z']

In [10]: bisect.insort_left(s1, 'y')

In [10]: s1
Out[10]: ['a', 'b', 'h', 'h', 'y', 'z']

In [11]: bisect.insort_right(s1, 'y1')

In [12]: s1
Out[12]: ['a', 'b', 'h', 'h', 'y', 'y1', 'z']

小应用场景:

import bisect
def get_score_level(score, scores=(60, 70, 80, 90), grades="EDCBA"):
    position = bisect.bisect(scores, score)
    return grades[position]
print(get_score_level(65))

可以不用那么一推if else了

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值