gpt4 book ai didi

python - 获取二维数组中最近的坐标

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:38 25 4
gpt4 key购买 nike

coordinates = [(-225.0, -299.5), (-150.0, 75.5), (0.0, 0.0), (225.0, 300.5)]

xy = (-222.4, -204.5)

将给定值 xy 与二维坐标列表进行比较并返回最近坐标的索引号的最佳方法是什么?

在此示例中,xy 将与坐标列表进行比较,从而返回最接近的坐标 (-225.0, -299.5),或者更理想的情况下,返回索引号 0。

我曾尝试使用 itertools 或 numpy 研究一种方法,但似乎无法理解如何在我的示例中获得我想要的结果。

最佳答案

使用 scipy.spatial.KDTree:

from scipy import spatial
import numpy as np
coordinates = [(-225.0, -299.5), (-150.0, 75.5), (0.0, 0.0), (225.0, 300.5)]
x = [(-222.4, -204.5)]
distance,index = spatial.KDTree(coordinates).query(x)
print(distance)
print(index)

kd-tree 方法是 O(N*log(N)) 并且比 Brute Force 方法要快得多,后者需要 O(N**2) 时间来获得足够大的 N。

关于python - 获取二维数组中最近的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53257607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com