[英]Find closest points between two lists of [[X,Y], [X,Y], ...] coordinates, in vanilla python
I have two lists of [x, y] coordinates (trimmed for ease of understanding).我有两个 [x, y] 坐标列表(为了便于理解而进行了修剪)。
How can I find the closest point between the two lists.如何找到两个列表之间的最近点。 ie.
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.我曾尝试按最高/最低 X 和 Y 值排序并进行比较,但没有成功,而且我不确定这是否是正确的路线。 The only leads I can find are for single values in lists, or importing a custom python library.
我能找到的唯一线索是列表中的单个值,或导入自定义 python 库。 I need this in vanilla python.
我需要这个原版 python。
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:您可以使用
min
function 的key
参数一步完成itertools
itertools.product
一个内置模块:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.