python 模块bisect

本文详细介绍了Python内置模块bisect的使用方法,包括bisect、bisect_left、bisect_right、insort、insort_left和insort_right等函数。通过实例演示了如何利用这些函数进行高效的列表插入操作和查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bisect是 python 的内置模块,主要用来排序
方法:

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


import bisect

li=[21,4,5,61,45,100]
li.sort()
print(li)
print(bisect.bisect(li,55))
print(bisect.bisect(li,45))
print(bisect.bisect_left(li,45))
print(li)
bisect.insort_right(li,5)
print(li)

说明
[4, 5, 21, 45, 61, 100]
4
4
3
[4, 5, 21, 45, 61, 100]
[4, 5, 5, 21, 45, 61, 100]

可以看到
bisect.bisect系列返回的是插入索引的位置
bisect.insort系列返回的是插入排序后返回的新的有序列表

demo
翻译流畅的python

import bisect
import sys
import bisect
import sys

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}    {2}{0:<2d}'


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


if __name__ == '__main__':
    if sys.argv[-1] == 'left':
        bisect_fn = bisect.bisect_left
    else:
        bisect_fn = bisect.bisect
    print('DEMO:', bisect_fn.__name__)
    print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK))
    demo(bisect_fn)

结果

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

ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'说明 format格式化函数

在这里插入图片描述
{0:2d} 第0个参数宽度为2
{1:2d} 第1个参数宽度为2
{2} 第2个参数
{0:<2d} 第0个参数,填充右边,宽度为2
d为输出整数的十进制方式

demo2 根据一个分数,查找他所对应的成绩

def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
        i = bisect.bisect(breakpoints, score)
        return grades[i]
[grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]

结果
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值