python - 如果在任何其他点的某个阈值内,则从列表中删除点
问题描述
我有从列表中过滤点的代码,它们之间的距离低于 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 循环只检查一个点然后跳转到下一个点。
我怎样才能让它在每一点检查所有数字。
解决方案
您的算法非常仔细地只检查最近添加到列表中的点,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)
推荐阅读
- arrays - 指向数组的指针的 Fortran 数组返回相同的地址
- discord - 如何在 discord.py 上阻止文本墙/重复文本
- javascript - 为什么箭头函数用于javascript中的惰性求值
- java - 为什么 H2 在自动创建模式之前尝试将数据加载到数据库中?
- css - 如何仅更改 Bootstrap 网格中最后一列的样式
- javascript - 尝试获取多个图像时,Angular observable 抛出状态码为 200 的错误
- android - 在图表上绘制 BLE 实时数据
- java - 使用 JCabi Java 读取 UTF-16 XML 文件
- javascript - RequireJS:“express”和“cors”的脚本错误,但不知道如何修复它
- bash - 在循环中询问用户输入,直到在命令行参数数组中找到匹配项