首页 > 解决方案 > 如果在任何其他点的某个阈值内,则从列表中删除点

问题描述

我有从列表中过滤点的代码,它们之间的距离低于 3:

import numpy
lst_x = [0,1,2,3,4,5,6,7,8,9,10]
lst_y = [9,1,3,2,7,6,2,7,2,3,8]
lst = numpy.column_stack((lst_x,lst_y))

diff = 3

new = []
for n in lst:
    if not new or ((n[0] - new[-1][0]) ** 2 + (n[1] - new[-1][1]) ** 2) ** .5 >= diff:
    new.append(n)

问题是输出是:

[array([0, 9]), array([1, 1]), array([4, 7]), array([6, 2]), array([7, 7]), array([8, 2]), array([10,  8])]

point[6,2]并且[8,2]彼此之间的距离小于 3 但它们在结果中,我相信这是因为 for 循环只检查一个点然后跳转到下一个点。

我怎样才能让它在每一点检查所有数字。

标签: pythonpython-3.xeuclidean-distance

解决方案


您的算法非常仔细地检查最近添加到列表中的点,new[-1]. 这是不够的。您需要另一个循环来确保检查. new像这样的东西:

for n in lst:
    too_close = False
    for seen_point in new:  
        # Is any previous point too close to this one (n)?
        if not new or ((n[0] - seen_point[0]) ** 2 +     \
                       (n[1] - seen_point[1]) ** 2) ** .5 < diff:
            too_close = True
            break

    # If no point was too close, add this one to the "new" list.
    if not too_close:
        new.append(n)

推荐阅读