【问题标题】:Using enumerate in nested loops [Python]在嵌套循环中使用枚举 [Python]
【发布时间】:2021-01-25 16:09:53
【问题描述】:

我有一个包含 (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 的某些属性吗?

【问题讨论】:

  • 对于初学者,不建议更改您正在循环的容器:stackoverflow.com/questions/1637807/…
  • 我同意你的看法,这不是一个好主意,但我认为除了在容器之间进行更改之外没有其他解决方案。
  • 能否在满足条件的基础上创建另一个列表,并在处理完成后用新列表覆盖原始列表?

标签: python list loops enumerate


【解决方案1】:

您可以迭代地构建一个包含满足条件的点的新列表。

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 数组来加快一点到多点的距离计算。

【讨论】:

  • 你的第二个循环会运行吗?我的意思是,spread_points 是一个空列表,您尝试遍历其中的每个元素。
  • 是的,当spread_points为空时,for循环else将运行(因为循环不是break退出的)然后spread_points将不再为空。跨度>
猜你喜欢
  • 2017-09-01
  • 2012-11-08
  • 1970-01-01
  • 2022-01-05
  • 2021-02-13
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多