如何计算存储在列表中的坐标之间的距离?

How to calculate distance between coordinates stored in a list?

所以我有两个列表,每个列表都包含多个点,如下所示:

list1 = [(1,2),(3,4),(5,6),(7,8),...]
list2 = [(1,1),(2,2),(3,3,),...]

(这些只是示例,因为我的普通数据最多包含 10.000 个点)

我设法用这些代码行计算了一个列表中的每个点与第二个列表中的每个点之间的距离:

dist = []
from math import sqrt

def distance(p1, p2):
    return sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)

for p1 in list1:
    for p2 in list2:
        d = distance(p1, p2)
        dist.append(d)

(注意:dist = []dist.append用于将计算的距离存储在列表中)

但事实上,对于我的分析,我只需要从 list1 中的点到 list2 中最近的点的距离!

为了让这更容易理解,我在此处绘制了列表中的要点: Plotted points from list

如你所见,对于每个蓝点我只想计算到最近的红点的距离,而不是所有的。 (我想这可以通过计算一个蓝点到所有红点的距离,然后只存储最小的距离,an/or 丢弃其他的)

有没有人知道如何做到这一点?

您可以映射一个列表,传入一个映射另一个列表的 lambda 函数,并找到最小距离:

list(map(lambda x: min(map(lambda y: distance(x, y), list2)), list1))

或作为列表理解:

[min((distance(x,y)) for y in list2) for x in list1]

正如您所说,列表很大,如果可以选择使用 numpy,它可能是一个很好的用例。它是一个(大型)库,针对 C 速度的数字和数组处理进行了优化。在这里你可以做:

import numpy as np

list1 = [(1,2),(3,4),(5,6),(7,8)]
list2 = [(1,1),(2,2),(3,3,)]

# build numpy arrays
arr1 = np.array(list1).reshape((len(list1), 1, len(list1[0]))) # add a dimension to allow broadcasting
arr2 = np.array(list2)

d = arr1 - arr2              # compute element wise difference on a (4,3,2) array
d2 = d * d                   # squares of above elements
ds = np.sum(d2, axis=2)      # sum the individual coordinates => square of distances
dsn = np.min(ds, axis=1)     # min of (square of) distance along list1
dist = np.sqrt(dsn)          # array (4) of minimum distance from a point from list1 to a point from list2

# all the operation in one single line, same result
dist2 = np.sqrt(np.min(np.sum(np.power(arr1 - arr2, 2), axis=2), axis=1))

它给出 distdist2(相同的值):

array([1.        , 1.        , 3.60555128, 6.40312424])

对于小数组不是很有用,因为加载 numpy 很昂贵,但对于大数组,纯 python 循环应该快得多。