Last active
June 9, 2020 04:22
-
-
Save jackz314/9990bdc5462097275787433c7235a671 to your computer and use it in GitHub Desktop.
Get element index closest to target element in a list of tuples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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