Home > database >  Find closest points between two lists of [[X,Y], [X,Y], ...] coordinates, in vanilla python
Find closest points between two lists of [[X,Y], [X,Y], ...] coordinates, in vanilla python

Time:01-23

I have two lists of [x, y] coordinates (trimmed for ease of understanding).

How can I find the closest point between the two lists. ie. if they're beacons on two islands coastlines, how can I find the two closest beacons?

coords1 = [[0.5896793603897095, 2.4871931076049805], [0.6417439579963684, 2.4339494705200195], [0.6417439579963684, 2.4871931076049805], [0.6157116293907166, 2.407327651977539], [0.6677762269973755, 2.4605712890625], [0.6157116889953613, 2.4871931076049805], [0.5896793603897095, 2.407327651977539], [0.6417439579963684, 2.407327651977539], [0.6547601222991943, 2.4738821983337402], [0.6547601222991943, 2.4472603797912598], [0.6026955246925354, 2.4871931076049805]]


coords2 = [[0.7719054222106934, 2.4605712890625], [0.7198407649993896, 2.407327651977539], [0.7979376912117004, 2.4605712890625], [0.7458730936050415, 2.4605712890625], [0.7198408246040344, 2.4339494705200195], [0.7198408246040344, 2.3807055950164795], [0.7328569293022156, 2.4472603797912598], [0.7849215269088745, 2.4605712890625], [0.7588892579078674, 2.4605712890625], [0.7458730936050415, 2.4472603797912598], [0.7198407649993896, 2.4472603797912598], [0.7198407649993896, 2.394016742706299], [0.7198407649993896, 2.4206385612487793]]
 
closestCoord1 = [] 
closestCoord2 = []

I have tried sorting by highest/lowest X and Y values and comparing but had no luck, and I'm unsure if that's the right route. The only leads I can find are for single values in lists, or importing a custom python library. I need this in vanilla python.

CodePudding user response:

You will need to find the distance between each pair of points. Then find the minimum.

You can do it in a single step using the key argument to the min function. itertools.product is used to find all pairs of points, but itertools is a built-in module:

import itertools

def sqdist(pts):
    p1 = pts[0]
    p2 = pts[1]
    return (p1[0]-p2[0])**2   (p1[1]-p2[1])**2

point_pairs = itertools.product(coords1, coords2)

closestCoord1, closestCoord2 = min(point_pairs, key=sqdist)

Try it online

  • Related