Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e046d2a

Browse files
committed
Add example of how to do key lookups with bisect().
1 parent 14eac1b commit e046d2a

1 file changed

Lines changed: 19 additions & 1 deletion

File tree

Doc/library/bisect.rst

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,22 @@ is a 'B', etc.
6868
>>> map(grade, [33, 99, 77, 44, 12, 88])
6969
['E', 'A', 'B', 'D', 'F', 'A']
7070

71-
71+
Unlike the :func:`sorted` function, it does not make sense for the :func:`bisect`
72+
functions to have *key* or *reversed* arguments because that would lead to an
73+
inefficent design (successive calls to bisect functions would not "remember"
74+
all of the previous key lookups).
75+
76+
Instead, it is better to search a list of precomputed keys to find the index
77+
of the record in question::
78+
79+
>>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
80+
>>> data.sort(key=lambda r: r[1]) # precomputed list of keys
81+
>>> keys = [r[1] for r in data]
82+
>>> data[bisect_left(keys, 0)]
83+
('black', 0)
84+
>>> data[bisect_left(keys, 1)]
85+
('blue', 1)
86+
>>> data[bisect_left(keys, 5)]
87+
('red', 5)
88+
>>> data[bisect_left(keys, 8)]
89+
('yellow', 8)

0 commit comments

Comments
 (0)