I have got a list of tuples with x,y values. I would like to find the closest x value's index in the list. Following is my code.
# list of coords
a = [(376, 220), (350, 218), (324, 216), (298, 214), (271, 211), (245, 210), (219, 208), (192, 205), (166, 204)]
to_find = (190, 210)
#grab a new list with only x axis elements
lst = []
for i in range(len(a)):
lst.append(a[i][0])
#list of all x coordinates
print(lst)
#find the min closest element
def min_closest(lst, K):
return lst[min(range(len(lst)), key=lambda i: abs(lst[i] - K))]
#print the corresponding index
print(lst.index(min_closest(lst, to_find[0])))
I formulated a new list with x values. Finally, I compared the x value of the search list with the x list to find the closest possible element. Later I grabbed its index. Is there any efficient way of doing so?