2

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?

  • Does this answer your question? [finding index of an item closest to the value in a list that's not entirely sorted](https://stackoverflow.com/questions/9706041/finding-index-of-an-item-closest-to-the-value-in-a-list-thats-not-entirely-sort) – tfw Nov 06 '19 at 09:07
  • no.. i tried it with no luck :( –  Nov 06 '19 at 09:08
  • What was the issue? The accepted answer seems to work to me, with minor modifications: It's the same as the accepted answer here. – tfw Nov 06 '19 at 09:13

3 Answers3

2

You did the entire thing, but took an extra step:

a = [(376, 220), (350, 218), (324, 216), (298, 214), (271, 211), (245, 210), (219, 208), (192, 205), (166, 204)]
to_find = (190, 210)

ix = min(range(len(a)), key = lambda x: abs(a[x][0] - to_find[0]))
print(ix)

Output:

7

Another way, would probably be faster:

a = [(376, 220), (350, 218), (324, 216), (298, 214), (271, 211), (245, 210), (219, 208), (192, 205), (166, 204)]
to_find = (190, 210)

min_diff, min_ix = 999999999, None
for ix, value in enumerate(a):
    diff = abs(to_find[0] - value[0])
    if diff < min_diff:
        min_diff, min_ix = diff, ix
print(min_ix)
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
1

Transform a to a numpy.array and then use np.argmin:

arr = np.array(a)
diffs = np.abs(arr - to_find)
arr[np.argmin(diffs[:, 0])]
#OUTPUT array([192, 205])
Aryerez
  • 3,417
  • 2
  • 9
  • 17
0

Try using scipy.spatial.distance.euclidean:

from scipy.spatial.distance import euclidean
a = [(376, 220), (350, 218), (324, 216), (298, 214), (271, 211), (245, 210), (219, 208), (192, 205), (166, 204)]
to_find = (190, 210)
print(min(a, key = lambda x: euclidean(x, to_find)))

Output:

(192, 205)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114