Python 的 bisect
模块通过二分查找算法实现对有序序列的高效搜索和管理。
一、核心搜索函数及特性
1. bisect.bisect_left
- 功能
返回元素在有序序列中第一个匹配位置左侧的插入索引。若元素已存在,插入位置为其左侧;若不存在,返回第一个大于该元素的索引。 - 示例
import bisect
lst = [1, 3, 3, 5]
index = bisect.bisect_left(lst, 3) # 返回 1
2. bisect.bisect_right(别名 bisect.bisect)
- 功能
返回元素在有序序列中最后一个匹配位置右侧的插入索引。若元素已存在,插入位置为其右侧;若不存在,返回第一个大于该元素的索引。 - 示例
index = bisect.bisect_right(lst, 3) # 返回 3
3. 参数说明
bisect.bisect_left(a, x, lo=0, hi=len(a))
- a: 必须为预先排序的列表。
- x: 待搜索元素。
- lo/hi: 可选参数,限定搜索范围。
三、使用示例
1. 基础搜索
a = [1, 4, 5, 6, 8, 12]
target = 5
pos = bisect.bisect_left(a, target) # 返回 2,表示元素5位于索引2处
2. 处理重复元素
ordered_list = [23, 34, 34, 59]
pos_left = bisect.bisect_left(ordered_list, 34) # 返回 1(左侧插入位置)
pos_right = bisect.bisect_right(ordered_list, 34) # 返回 3(右侧插入位置)
上一篇: