【问题标题】:Remove point from list if within certain threshold of any other point如果在任何其他点的某个阈值内,则从列表中删除点
【发布时间】:2018-10-06 12:46:55
【问题描述】:

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

如何让它检查每个点的所有数字。

【问题讨论】:

  • 当你得到解决方案时,请记得给有用的东西投票并接受你最喜欢的答案(即使你必须自己写),这样 Stack Overflow 才能正确存档问题。跨度>

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


【解决方案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)

【讨论】:

    猜你喜欢
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2017-10-21
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多