Skip to content

Instantly share code, notes, and snippets.

@ericremoreynolds
Last active August 9, 2022 20:44
Show Gist options
  • Save ericremoreynolds/2d80300dabc70eebc790 to your computer and use it in GitHub Desktop.
Save ericremoreynolds/2d80300dabc70eebc790 to your computer and use it in GitHub Desktop.
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
@xmedeko
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