Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Key-like functionality recipe for Python's bisect functions
class KeyifyList(object):
def __init__(self, inner, key):
self.inner = inner
self.key = key
def __len__(self):
return len(self.inner)
def __getitem__(self, k):
return self.key(self.inner[k])
if __name__ == '__main__':
import bisect
L = [(0, 0), (1, 5), (2, 10), (3, 15), (4, 20)]
assert bisect.bisect_left(KeyifyList(L, lambda x: x[0]), 3) == 3
assert bisect.bisect_left(KeyifyList(L, lambda x: x[1]), 3) == 1

This comment has been minimized.

Copy link

xmedeko commented Dec 14, 2018

Wonderful, works for any Sequence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.