I read that question about how to use bisect
on a list of tuples, and I used that information to answer that question. It works, but I\'d like a more generic so
bisect
supports arbitrary sequences. If you need to use bisect
with a key, instead of passing the key to bisect
, you can build it into the sequence:
class KeyList(object):
# bisect doesn't accept a key function, so we build the key into our sequence.
def __init__(self, l, key):
self.l = l
self.key = key
def __len__(self):
return len(self.l)
def __getitem__(self, index):
return self.key(self.l[index])
Then you can use bisect
with a KeyList
, with O(log n) performance and no need to copy the bisect
source or write your own binary search:
bisect.bisect_right(KeyList(test_array, key=lambda x: x[0]), 5)