从API我得到一个包含不同坐标的“列表列表”:
List = [[1.0, 2.5, 3.6], [2.02, 2.3, 3.1], [1.5, 6.5, 3.9]]
我必须找到两个坐标之间的最小距离。 我做了类似的事情:
MinDist = 9999999999.
for Coord1 in List:
for Coord2 in List:
if Coord1 != Coord2:
Dist = CalcDistance(Coord1,Coord2)
if Dist < MinDist:
MinDist=Dist
是否有更“智能”(且更快)的方式来获取此信息?
答案 0 :(得分:1)
假设CalcDistance
类似于以下内容,您可以使用min
和一个关键功能以及itertools.combinations
from itertools import zip_longest, combinations
def CalcDistance(a, b):
return (sum((x-y)**2 for x, y in zip_longest(a, b, fillvalue=0)))**.5
List = [[1.0, 2.5, 3.6], [2.02, 2.3, 3.1], [1.5, 6.5, 3.9]]
print(min(combinations(List, 2), key=lambda x: CalcDistance(*x)))
# ([1.0, 2.5, 3.6], [2.02, 2.3, 3.1])
答案 1 :(得分:1)
为什么不使用内置算法:
import numpy as np
from scipy.spatial.distance import pdist, squareform
List = [[1.0, 2.5, 3.6], [2.02, 2.3, 3.1], [1.5, 6.5, 3.9]]
dist_mat = squareform(pdist(List, CalcDistance))
np.fill_diagonal(dist_mat,np.inf)
i,j = np.unravel_index(dist_mat.argmin(), dist_mat.shape)
print((List[i],List[j]))
上面的代码结合了Find the index of the min value in a pdist condensed distance matrix和Numpy minimum in (row, column) format