问题描述
我有一个包含 (x,y,z) 的三元组列表 points
,其中 x 是 x 坐标,y 是 y 坐标,z 是幅度。现在我想检查列表中的任何点是否在列表中其他点的特定半径内。如果是这样,则必须删除半径中的点。因此我做了以下代码。
radius = 20
for _,current_point in enumerate(points):
# get the x and y coordinate of the current point
current_x,current_y = current_point[0],current_point[1]
for _,elem in enumerate(points):
# check if the second point is within the radius of the first point
if (elem[0] - current_x)**2 + (elem[1] - current_y)**2 < radius**2:
# remove the point if its within the radius
points.remove(elem)
当我运行这个列表时,列表仍然包含在另一个点半径内的点。我在这里遗漏了 enumerate
的某些属性吗?
解决方法
您可以迭代地构建一个包含满足条件的点的新列表。
radius = 20
spread_points = []
for point in points:
# get the x and y coordinate of the current point
current_x,current_y = point[0],point[1]
for sp in spread_points:
# check if the second point is within the radius of the first point
if (sp[0] - current_x)**2 + (sp[1] - current_y)**2 < radius**2:
break
else:
spread_points.append(point)
对于更有效的算法,也许您可以使用 https://en.wikipedia.org/wiki/Quadtree。
或者只是为了加快速度,您可以使用 numpy 数组来加快一点到多点的距离计算。