python: 求两个数组中两点之间的最小距离

python: finding smallest distance between two points in two arrays

我有两个包含一系列元组 (x,y) 的列表,代表笛卡尔平面上的不同点:

a = [(0, 0), (1, 2), (1, 3), (2, 4)]
b = [(3, 4), (4, 1), (5, 3)]

我想找到距离较近的两个点(每个列表一个,不在同一个列表中),在这种特定情况下:

[((2, 4), (3, 4))]

其距离等于 1。我使用的是列表理解,如:

[(Pa, Pb) for Pa in a for Pb in b \
if math.sqrt(math.pow(Pa[0]-Pb[0],2) + math.pow(Pa[1]-Pb[1],2)) <= 2.0]

但这使用了一个阈值。有没有办法在某处或类似的地方附加一个 argmin() 并只获得对 [((xa, ya), (xb, yb))] 最小距离?谢谢。

只需使用列表理解和 min 如下:

dist = [(Pa, Pb, math.sqrt(math.pow(Pa[0]-Pb[0],2) + math.pow(Pa[1]-Pb[1],2)))
        for Pa in a for Pb in b]

print min(dist, key=lambda x:x[2])[0:2]
import numpy
e = [(Pa, Pb) for Pa in a for Pb in b]
e[numpy.argmin([math.sqrt(math.pow(Pa[0]-Pb[0],2) + math.pow(Pa[1]-Pb[1],2)) for (Pa, Pb) in e])]

将按照您的建议使用 argmin 和 return ((2, 4), (3, 4))

类似于 DevShark 的解决方案,但有一些优化技巧:

import math
import itertools
import numpy as np

def distance(p1, p2):
    return math.hypot(p2[0] - p1[0], p2[1] - p1[1])

a = [(0, 0), (1, 2), (1, 3), (2, 4)]
b = [(3, 4), (4, 1), (5, 3)]

points = [tup for tup in itertools.product(a, b)]

print(points[np.argmin([distance(Pa, Pb) for (Pa, Pb) in points])])

您还可以将 scipy.spatial 库与以下内容一起使用:

import scipy.spatial as spspat
import numpy as np
distanceMatrix = spspat.distance_matrix(a,b)
args = np.argwhere(distanceMatrix==distanceMatrix.min())
print(args)

这将为您 return 以下内容:array([[3, 0]]) ,即每个列表中点的位置。 这应该也适用于任何维度。