[英]How do I find the coordinates of the two closest points to my point in a list
I have a list of values and a given point and I want to find the coordinates of the two closest points (one inferior and one superior).我有一个值列表和一个给定点,我想找到两个最近点的坐标(一个下级和一个上级)。
For example:例如:
list = [0, 0.5, 1, 1.5, 2, 2.5, 3]
point = 0.7
I want my return value to be [1, 2] since 0.7 is between 0.5 and 1.我希望我的返回值为 [1, 2],因为 0.7 介于 0.5 和 1 之间。
Any idea of how to do this?知道如何做到这一点吗?
Assuming the given list is always sorted as it is in your example and that it has for sure one value below and one value above your given point, then you can loop over the list until you find a value larger than the given point and then return a list containing that index and the index below it.假设给定列表始终按照您的示例中的方式排序,并且它肯定在给定点下方有一个值,在给定点上方有一个值,那么您可以遍历列表,直到找到一个大于给定点的值,然后返回包含该索引及其下方索引的列表。
def two_closest(_list, point):
for index, value in enumerate(_list):
if value > point:
return (index-1, index)
raise Exception("Malformed parameters")
For larger lists, you could speed this up with binary search or other heuristics.对于较大的列表,您可以使用二分搜索或其他启发式方法加快速度。 For example, you said your list is created by np.linespace, you could find the exact place your coordinate would lie between if you knew how the list was created.
例如,您说您的列表是由 np.linespace 创建的,如果您知道列表是如何创建的,您可以找到您的坐标所在的确切位置。
you can compute distances and then exploit numpy.argsort
:您可以计算距离,然后利用
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])
If list
is in sorted order you can use python's built-in binary search library.如果
list
按排序顺序,您可以使用 python 的内置二进制搜索库。 It's very fast:它非常快:
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))
which prints:打印:
[1, 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.