Skip to content

Instantly share code, notes, and snippets.

@jackz314
Last active June 9, 2020 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackz314/9990bdc5462097275787433c7235a671 to your computer and use it in GitHub Desktop.
Save jackz314/9990bdc5462097275787433c7235a671 to your computer and use it in GitHub Desktop.
Get element index closest to target element in a list of tuples
# Modified from solution for numbers here: https://stackoverflow.com/a/12141511/8170714
# Tuple comparison solution from here: https://stackoverflow.com/a/31779268/8170714
def take_closest(self, list, element, idx=0):
"""
Assumes myList is sorted. Returns closest value to element (tuple).
When comparing not all elements in tuple, set all other locations in tuple to nothing (e.g. (X,Y,)).
idx: index (or slice) for the comparing target elements
If two elements are equally close, return the smaller element.
"""
pos = bisect_left(list, element)
if pos == len(list):
return pos-1
before = list[pos - 1]
after = list[pos]
if after[idx] - element[idx] < element[idx] - before[idx]:
return pos # after's idx
else:
return pos - 1 # before's idx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment