成对计算两组点之间的距离

Pairwise calculations of distances between two sets of points

我在 Python 中进行成对计算时遇到了一些麻烦。

我有两组节点(例如供应商和客户)。

我想计算一个客户到所有供应商的距离,并保存最短的距离。这应该为所有客户循环播放。

我意识到我将不得不使用两个 for 循环和一个 if 函数。但是我不明白如何在循环时从正确的点select坐标。

感谢您的回复! 更多信息: - 半正弦距离 - 必须将第 1 组中的每个点与第 2 组中的所有点进行比较 - 这就是我到目前为止的内容

import urllib.parse
from openpyxl import load_workbook, Workbook
import requests
from math import radians, cos, sin, asin, sqrt

"""load datafile"""
workbook = load_workbook('Macro.xlsm')
Companysheet = workbook.get_sheet_by_name("Customersheet")
Networksheet = workbook.get_sheet_by_name("Suppliersheet")

"""search for column with latitude/longitude - customers"""
numberlatC = -1
i = 0
for col in Customersheet.iter_cols():
    if col[2].value == "Latitude" :
        numberlatC = i
    i+=1

numberlongC = -1
j = 0
for col in Customersheet.iter_cols():
    if col[2].value == "Longitude" :
        numberlongC = j
    j+=1


latC = [row[numberlatC].value for row in Companysheet.iter_rows() ]
longC = [row[numberlongC].value for row in Companysheet.iter_rows()]

# haversine formula 
    dlon = lonC - lonS 
    dlat = latC - latS 
    a = sin(dlat/2)**2 + cos(latC) * cos(latS) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles
    distance = c*r 
    distances.append([distance])
    return distances

customers = [latC, longC]

谢谢!

这应该会给您大致的思路。在下面的示例中,我只使用了常规坐标,但是,您应该能够将其转换为您的需要。

supplier = [(1,3),(2,4),(8,7),(15,14)]
customer = [(0,2),(8,8)]

def CoordinatesDistance(A, B):
    import math
    x1, x2 = A
    y1, y2 = B
    return math.sqrt(math.exp((x2-x1)+(y2-y1)))

def shortest_distance_pair(Cust, Sup):
    pairs = []
    for X in Cust:
        shortest_distance = 999999
        for Y in Sup:
            distance = CoordinatesDistance(X,Y)
            #customer_distance.append(distance)
            if distance < shortest_distance:
                shortest_distance = distance
                sdp = (X,Y)
        pairs.append(sdp)
    return pairs

打印(shortest_distance_pair(客户,供应商))

print(shortest_distance_pair(customer,supplier))
[((0, 2), (8, 7)), ((8, 8), (8, 7))]

现在,如果您创建两个列表,1. 客户坐标,2. 供应商坐标;你应该能够利用上面的内容。