简体   繁体   中英

pythonic way of comparing values looping over lists

From an API i got a "list of lists" containing different coordinates:

List = [[1.0, 2.5, 3.6], [2.02, 2.3, 3.1], [1.5, 6.5, 3.9]]

I have to find the minimum distance between two coordinates. I did something like:

MinDist = 9999999999.
for Coord1 in List:
    for Coord2 in List:
        if Coord1 != Coord2:
            Dist = CalcDistance(Coord1,Coord2)
            if Dist < MinDist:
                MinDist=Dist

Is there a more "intelligent" (and faster) way to get this information?

Assuming CalcDistance is something like the below, you could use min and a key function together with 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])

Why not use a built in algorithm:

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]))

The code above combines Find the index of the min value in a pdist condensed distance matrix and Numpy minimum in (row, column) format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM