python - 在数组中查找不等于给定点的最近点
问题描述
我有一个点和一组值。我希望在数组中找到最近的点 y,使得 x != y。目前我在 Python 中使用标准的 Scipy KDTree 方法,但这不仅仅考虑独特的点。是否有任何解决方法或是否需要手动实施?谢谢!
解决方案
2D 阵列解决方案:我回收了大部分与以前相同的方法,但这次它应该适用于您的结构
import math
X = [0,0] # Your cooridinate
x1 = X[0]
y1= X[1]
array = [[1,1],[0,1],[1,0],[-2,2]] # Sample array of data
smallestDistance = 9999 # Make it big so it can be replaced immediately, essentially just a placeholder
for point in array:
x2 = point[0]
y2 = point[1]
separation = math.hypot(x2 - x1, y2 - y1) #Distance equation in easy format
if separation < smallestDistance and separation!=0: # Could make this <= instead of < if you want to replace any ties for closest point
smallestDistance = separation
closestPoint = point
print(f"Nearest cooridinate = {closestPoint}, separation from {X} is: {smallestDistance}")
一维数组的旧解决方案:我不太确定你的数组的结构是什么,但据我所知,你有一个一维数组和一个给定的值;您想要数组中最接近原始值的唯一值。如果这是正确的,那么快速而肮脏的解决方案可能类似于:
smallestDifference = 99999999 #Make this some large number
y = array[someindex]
for thing in array:
difference = abs(thing-y)
if difference<smallestDifference & difference != 0: #Must be closer than the last recorded closest point, AND non-zero i.e. a unique point
smallestDifference = difference #New smallest distance between points
closestPoint = thing #Record the new closest point
print(f"x = {closestPoint}, |y-x| = {smallestDifference}")
如果这是一个 >1d 数组并且可能不是最快的解决方案,可能会有点棘手,因为它必须检查每个点..但可能会完成工作:-)
推荐阅读
- wpf - 将任何旧的 WPF 几何转换为 PathFigureCollection?
- c# - EntityFrameworkCore - 将 DbSet 过滤到另一个实体上的单个属性
- powershell - 测试路径总是返回 False
- pytorch - 如何在 PyTorch 中为非图像数据创建小批量?
- powershell - 无需流式阅读器即可快速搜索大型 .log 以查找特定字符串
- c# - 如何添加 Quickbooks 在线支付服务?
- docker - 服务更新期间带有 traefik 和 docker swarm 的网关错误
- php - 在模型 [] 上调用未定义的关系 []
- gcloud - 基因组学管道上的抢占式机器
- heroku - 疑难解答 rails 6、bootstrap 4、heroku 上的 webpacker