如何在列表中找到离我的点最近的两个点的坐标

How do I find the coordinates of the two closest points to my point in a list

我有一个值列表和一个给定点,我想找到最近的两个点(一个下一个上)的坐标。

例如:

list = [0, 0.5, 1, 1.5, 2, 2.5, 3]
point = 0.7

我希望我的 return 值为 [1, 2],因为 0.7 介于 0.5 和 1 之间。

知道怎么做吗?

假设给定的列表总是按照你的例子排序,并且它肯定有一个低于你给定点的值和一个高于你给定点的值,那么你可以遍历列表直到你找到一个大于给定点的值给定点,然后 return 包含该索引及其下方索引的列表。

def two_closest(_list, point):
    for index, value in enumerate(_list):
        if value > point:
            return (index-1, index)
    raise Exception("Malformed parameters")

对于较大的列表,您可以使用二进制搜索或其他试探法来加快速度。例如,你说你的列表是由 np.linespace 创建的,如果你知道列表是如何创建的,你可以找到你的坐标之间的确切位置。

你可以计算距离然后利用 numpy.argsort:

import numpy as np

def closest_n_indexes(distances, n=2):
    return np.argsort(distances)[:n]

point_list = [0, 0.5, 1, 1.5, 2, 2.5, 3]
point = 0.7

distances = [abs(p-point) for p in point_list]

closest_n_indexes(distances)
Out[8]: array([1, 2])

如果 list 已排序,您可以使用 python 的内置二进制搜索库。非常快:

import bisect

def get_bracket(lst, target):
    lindex = bisect.bisect_right(lst, target) - 1
    rindex = lindex + 1
    return [lindex, rindex]

print(get_bracket([0, 0.5, 1, 1.5, 2, 2.5, 3], 0.7))

打印:

[1, 2]