我有以下纬度和经度列表。
[(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 :(得分:1)
这假定索引包装并且'near'被定义为1个单位。对于列表中的每个元素,对10个周围元素执行距离检查,如果它们在1之内,则添加到字典中。
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]:
这个很长,所以你可能想把它分成几行,但它就是这样做的。