如果在任何其他点的特定阈值内,则从列表中删除点

时间:2018-04-25 22:57:42

标签: python python-3.x euclidean-distance

我的代码可以过滤列表中的点,它们之间的距离低于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])]

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

如何在每个点检查所有数字。

1 个答案:

答案 0 :(得分:1)

您的算法会非常仔细地检查最近添加到列表中的点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)