繁体   English   中英

在嵌套循环中使用枚举 [Python]

[英]Using enumerate in nested loops [Python]

我有一个包含 (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 arrays 来加快一点到多点的距离计算。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM