Skip to main content
 首页 » 编程设计

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

2025年01月19日14oomusou

我有代码可以从列表中过滤点,这些点之间的距离小于 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循环只检查一个点然后跳到下一个点。

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

请您参考如下方法:

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