2017-07-07 60 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