all Python 3bisectterm
Range lookups with bisect()
usage
An idiom from the bisect docs: bisect over a list of breakpoints yields the range index — an O(log n) table lookup instead of an if/elif chain.
Syntax
i = bisect.bisect(breakpoints, x) # номер диапазона
labels[i] # метка диапазона
The label list must be exactly one longer than the list of breakpoints; otherwise extreme values raise IndexError or, worse, quietly return the wrong label. bisect() is bisect_right, so a value equal to a breakpoint falls into the upper range — switch to bisect_left if boundaries should belong to the lower one. The breakpoints themselves must be in ascending order; nothing checks that for you.
Examples
import bisect
breaks, letters = [60, 70, 80, 90], 'FDCBA'
print(letters[bisect.bisect(breaks, 33)]) # → 'F'
print(letters[bisect.bisect(breaks, 70)]) # → 'C' (граница уходит вверх)
print(letters[bisect.bisect(breaks, 89)]) # → 'B'
print(letters[bisect.bisect(breaks, 100)]) # → 'A'
print(letters[bisect.bisect_left(breaks, 70)]) # → 'D' (bisect_left оставляет границу внизу)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy