我有一个大约40个2D点(x和y)的列表。我想要一个从列表中的第一个点开始的脚本(例如,180,0)并找到从列表到该第一个点(180,0)的最近点。一旦找到最近点,它应该再次做同样的事情(所以最近点成为第一点),而不使用已经使用过的点(180,0)。这样做直到每一点都被使用了。通过这种方式,我的随机列表应该被排序成一个点列表,成为一个流畅的线路径。到目前为止我的代码看起来像这样:
def arrange_points(points):
# arranges all 2D points in a fluent and consistent linepath order
size = len(points) #number of elements in list
di = [] #list containing all distances from start point
start_point = points[0]
for i in range (size):
next_points = points[i]
dist = math.sqrt((next_points[0] - start_point[0])**2 + (next_points[1] - start_point[1])**2) #distance of start point to all other points
di.append(dist)
ln = min(filter(None, di)) # smallest distance from start point, except 0
f = di.index(ln) # finds place of ln in list di
next_point = points[f] # retrieves corresponding point from points, that corresponds to ln
return di
return next_point
di = arrange_points(points)
# 0 and previous points cannot be taken
这就是我的linepath现在的样子:
这就是它应该是这样的:
绘制的点看起来像这样:(错误的顺序)所以基本上如果我从180,0开始并继续跟随最近的点(不让代码返回),它应该最终以正确的顺序结束列表。
有谁可以帮我处理我的代码?
答案 0 :(得分:1)
IIUC,你可以这样做:
def get_nearest(points, coord):
"""Return closest point to coord from points"""
dists = [(pow(point[0] - coord[0], 2) + pow(point[1] - coord[1], 2), point)
for point in points] # list of (dist, point) tuples
nearest = min(dists)
return nearest[1] # return point only
next_point = points.pop(0) # get first point
line_path = []
line_path.append(next_point)
while len(points) > 1:
next_point = get_nearest(points, next_point)
line_path.append(next_point)
points.remove(next_point)
line_path.extend(points) # add last point