Skip to main content
 首页 » 编程设计

python之计算 Python 中两个大列表的每个元素的距离

2024年10月24日15lvdongjie

我有两个大的元组列表(大小 > 5000),其中包含这样的坐标:

l1 = [ (33.5779, -111.925), 
 (33.5738, -111.906), 
 (33.5556, -111.899), 
... 
 (33.5646, -111.915), 
 (33.5733, -111.863)] 
 
l2 = [ (33.4318, -111.938), 
 (33.5228, -111.9), 
 (33.5387, -111.885), 
... 
 (33.5264, -111.925), 
 (33.538, -111.888)] 

我想找到满足以下条件的组合:

distance <= arbitraryDistance 

距离是:

 from geopy.distance import great_circle 
 great_circle((longitude1,latitude1), (longitude2,latitude2)) 

最快的方法是什么?

请您参考如下方法:

我找到的一个相对较快的解决方案是使用函数 cdist来自 scipy.spatial.distance

它计算两个列表中每个点组合之间的欧氏距离。尽管它不计算以米为单位的距离,但以度为单位,我仍然可以将我的米要求转换为度数。

所以我目前的解决方案是这样的:

from scipy.spatial.distance import cdist 
l1 = [ (33.5779, -111.925), 
 (33.5738, -111.906), 
 (33.5556, -111.899), 
... 
 (33.5646, -111.915), 
 (33.5733, -111.863)] 
 
l2 = [ (33.4318, -111.938), 
 (33.5228, -111.9), 
 (33.5387, -111.885), 
... 
 (33.5264, -111.925), 
 (33.538, -111.888)] 
 
distanceRequired = 0.02 #arbitrary number in degrees 
 
matrixOfDistances = cdist(l1,l2) 
for index1,value1 in enumerate(matrixOfDistances): 
  isABusinessOpportunity = True 
  for index2,value2 in enumerate(value1): 
    if value2 <= distanceRequired: 
      isABusinessOpportunity = False 
        break 
 
  if isABusinessOpportunity: 
    print "The combination is:" + str(index1) + str(index2)