2017-07-07 65 views
-3

我有以下的纬度和经度列表。从坐标列表连接附近坐标

[(52.5, 12.0), (36.0, -0.5), (50.0, -17.5), (52.0, 13.0), (52.0, 13.0), (50.0, -16.5), (37.5, 1.5), (37.5, 1.5), (46.0, 20.0), (37.5, 1.5), (46.0, 20.0), (50.0, -15.0)]

我要连接只有相互靠近的点。如果每个点之间的索引差异小于5(例如),我也只想连接。

我最初正在寻找一种连接所有点的方法,只有当绘制的线条在一定的长度以下。不知道这是否可能在python中?

非常感谢提前。

+0

你是什么意思的指数差异? x坐标,y坐标,欧氏距离之间的差异? 你到目前为止尝试过什么? –

+0

指标距离换行吗?例如,在第一个元素包含最后一个元素之前是5? – bendl

+0

你的代码到目前为止是什么样的? :https://stackoverflow.com/help/how-to-ask – patrick

回答

1

这假定索引换行,'near'定义为1个单位。对于列表中的每个元素,对10个周围元素执行距离检查,如果它们在彼此之内,则添加到字典中。

nearby = {}               # This will hold 'connected' elements 
for index, element in enumerate(l):         # Enumerate through the list l, keeping track of index 
    for other in l[index-5: index+5]:        # For each element 5 before and 5 after 
     if sum((a - b)**2 for a, b in zip(element, other))**.5 < 1 and element != other: 
                    # If other < 5 away from element and other not element 
      if element not in nearby.keys():       # If element isn't already in the dicitonary 
       nearby[element] = [other]       # Add it and reference other 
      else:             # Otherwise 
       nearby[element].append(other)      # Add other to the list of nearby elements 

如果指数不换,你可以改变线for other in l[index-5: index+5]:到包括列表的开始和结束检查。以下是我的做法:

for other in l[index-5 if index-5 > 0 else 0 : index+5 if index+5 < len(l) else len(l) -1]: 

这很长,所以你可能想把它分成几行,但它的确是这样做的。

+0

假设OP已经评论他认为〜100靠近,考虑将<1更改为<100,并且当您运行目前的代码时,结果为空字典。 –

+0

〜100是以千米为单位,他的分数在经度和纬度上,所以我相信<100是世界上最多的。另外,我几乎可以肯定它没有。我已经在我的机器和TIO上测试过它,它在两个地方都能正常工作。 – bendl

+0

https://tio.run/##hZDdboMwDIXv8xTeXdKFKMDSStXYiyAuguqqaBAQUGls2rOz/LGq06b5Bh/[email protected]/[email protected]wxQ7NbCWguXY46hlpy44EbDiuny/[email protected]@gUo5klaBX8XFp6uHQWqIYGa7XaZH6s51G7qezPQuCMPuzDLCOesQJvT9wEPRSjfnKP7BpjeXxneQbziMlF2D7sI5TI2Vfa9Sm9b3ZHumn97hR4GNCcatiZkGBsz0wCxdf0C – bendl