How do I find the index of a list in a list that contains the point closest (by distance) to the point "n"?

The answer must be 1, because the nearest value in the 1 index list.


point = [
    [(540, 420), (620, 300), (370, 140), (250, 390)],
    [(60, 30), (550, 310), (50, 520)],
    [(200, 500), (370, 390), (170, 200)]
]

n = (20, 15)

items = []
for idx, area in enumerate(point):
            for x, y in area:
                items.append((idx, x, y))
Author: sheviv, 2019-06-04

1 answers

def squared_dist(p1, p2):
     return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)

def dist(p1, p2):
     return squared_dist(p1, p2) ** .5

items = [(i,x,y) for i,r in enumerate(point) for x,y in r]


nearest_point = min(items, key=lambda x: squared_dist(n, x[1:]))

Result:

In [95]: nearest_point
Out[95]: (1, 60, 30)

In [96]: nearest_point[0]
Out[96]: 1

items - a list of points (tuples), where the first element is the index of the row / list containing the given point, and the other two are the coordinates x and y:

In [17]: items
Out[17]:
[(0, 540, 420),
 (0, 620, 300),
 (0, 370, 140),
 (0, 250, 390),
 (1, 60, 30),
 (1, 550, 310),
 (1, 50, 520),
 (2, 200, 500),
 (2, 370, 390),
 (2, 170, 200)]
 2
Author: MaxU, 2019-06-05 07:49:15