← 中文资源

简体中文版本

bisect 插入即保持有序

bisect 让列表始终保持有序:insort 按序插入免掉先 append 再 sort,bisect_left 与 bisect_right 回答区间与重复问题,key 参数按投影比较。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

[10, 50, 75, 100, 500]
amount 120 falls in tier 3
[(1, 'backup'), (2, 'index'), (2, 'report'), (3, 'cleanup')]
1 2

实现说明

演示用的数据放在这几个模块级绑定中:thresholds、amount、idx、jobs。

使用要点

  • 直接运行文件,输出会带上标签,比如 amount——输出的每一行都能指回产生它的那次调用。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 全部导入都来自标准库:bisect。 跨调用保留的状态放在这些顶层绑定里:thresholds、amount、idx。

代码示例

import bisect

# bisect 维护「已排序列表」的不变量:插入点即查找点
thresholds = [10, 50, 100, 500]

# insort 按序插入,无需先 append 再 sort
bisect.insort(thresholds, 75)
print(thresholds)

# bisect_right 给出插入点:右起第一个大于 amount 的位置
amount = 120
idx = bisect.bisect_right(thresholds, amount)
print(f"amount {amount} falls in tier {idx - 1}")

# key 参数(3.10+):对 (priority, task) 元组按第一维比较
jobs = [(3, "cleanup"), (1, "backup"), (2, "index")]
jobs.sort()
bisect.insort(jobs, (2, "report"))
print(jobs)

# 与手写二分等价:实现经过优化,语义只有一处定义
print(bisect.bisect_left(thresholds, 50), bisect.bisect_right(thresholds, 50))