Using bisect in a list of tuples?
In some cases just the simple
bisect(list_of_tuples, (3, None))
will be enough.
Because None
will compare less than any integer, this will give you the index of the first tuple starting with at least 3, or len(list_of_tuples)
if all of them are smaller than 3. Note that list_of_tuples
is sorted.
You can separate out the values into separate lists.
from bisect import bisect
data = [(3, 1), (2, 2), (5, 6)]
fst, snd = zip(*data)
idx = bisect(fst, 2)
Note however, that for bisect
to work, your data really should be ordered...
Check the bottom section of the documentation: http://docs.python.org/3/library/bisect.html. If you want to compare to something else than the element itself, you should create a separate list of so-called keys. In your case a list of ints containing only [1] of the tuple. Use that second list to compute the index with bisect. Then use that to both insert the element into the original (list of tuples) and the key ([1] of the tuple) into the new list of keys (list of ints).