bisect
— 数组二分算法
¶
源代码: Lib/bisect.py
This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over linear searches or frequent resorting.
The module is called
bisect
because it uses a basic bisection algorithm to do its work. Unlike other bisection tools that search for a specific value, the functions in this module are designed to locate an insertion point. Accordingly, the functions never call an
__eq__()
method to determine whether a value has been found. Instead, the functions only call the
__lt__()
method and will return an insertion point between values in an array.
提供下列函数:
- bisect. bisect_left ( a , x , lo = 0 , hi = len(a) , * , key = None ) ¶
-
Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a , the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to
list.insert()假定 a is already sorted.The returned insertion point ip partitions the array a into two slices such that
all(elem < x for elem in a[lo : ip])is true for the left slice andall(elem >= x for elem in a[ip : hi])is true for the right slice.key 指定 关键函数 of one argument that is used to extract a comparison key from each element in the array. To support searching complex records, the key function is not applied to the x 值。
若 key is
None, the elements are compared directly and no key function is called.3.10 版改变: 添加 key 参数。