Python 两组点之间距离的成对计算
我在用Python进行两两计算时遇到了一些麻烦 我有两组节点(例如供应商和客户)Python 两组点之间距离的成对计算,python,python-3.x,loops,pairwise,Python,Python 3.x,Loops,Pairwise,我在用Python进行两两计算时遇到了一些麻烦 我有两组节点(例如供应商和客户) 集合1:多个供应商的SupplierCO=(Xco,Yco) 集合2:多个客户的客户CO=(Xco,Yco) 我想计算客户和所有供应商之间的距离,并保存最短距离。这应该为所有客户循环 我意识到我必须使用两个for循环和一个if函数。但我不明白在循环时如何从正确的点选择坐标 感谢您的回复! 更多信息: -哈弗森距离 -必须将集合1中的每个点与集合2中的所有点进行比较 -这就是我到目前为止所做的 import ur
- 集合1:多个供应商的SupplierCO=(Xco,Yco)
- 集合2:多个客户的客户CO=(Xco,Yco)
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
现在,如果创建两个列表,1。客户协调,和2。供应商协调;您应该能够利用上述信息。您对答案的期望是什么?我们需要你的数据给你任何具体的代码。有相当多的信息缺失。欧几里德距离、哈弗森距离还是其他距离?请显示模板代码。看来你的方法是合理的,那么它落在哪里了?如果Djikstra有节点和顶点,可能是他。@mishavacic好的,我错过了“最短距离”部分。你可能是对的。如果我用谷歌搜索你确切的问题标题,你的问题就是第一个结果。非常感谢菲利普!另外一个问题:如何获取[(X,Y),(X,Y)]格式的数据?我可以读取列表中的所有Xco和所有Yco,但如何合并它们?Grts!这是一个不同的问题,你应该接受答案。但是,在您的情况下,您有
客户=[latC,longC]
。要在列表中创建一对坐标,只需添加括号customers=[(latC,longC)]
。要在列表中添加更多坐标:customers.append((latC,longC))
再次感谢!目前我的代码中有一个“ValueError:太多的值无法解压缩(预期为2)”。。我看不出这是什么原因。谢谢请将其作为新问题添加。然后其他人也能找到答案:)
print(shortest_distance_pair(customer,supplier))
[((0, 2), (8, 7)), ((8, 8), (8, 7))]