在已排序的python列表中,找到最接近目标值的值及其在列表中的索引 [英] In a python list which is sorted, find the closest value to target value and its index in the list
本文介绍了在已排序的python列表中,找到最接近目标值的值及其在列表中的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在python的排序列表中获取最接近的值及其索引.
I am trying to get both the closest value and its index in a sorted list in python.
在MATLAB中,可以通过以下方式实现:
In MATLAB this is possible with:
[closest_val,index] = min(abs(array - target))
我想知道是否可以通过python实现类似的方法.
I was wondering if there is a similar way this can be implemented in python.
我见过一个可以做一个或另一个的帖子,但是我还没有看到两者都在一起做.
I've seen posts which do one or the other, but I haven't seen both done together.
Link to finding closest value in list post.
推荐答案
bisect
,因为该列表未排序.在这里,我们没有相同的问题,我们可以使用bisect
作为其提供的速度:
bisect
wasn't used in the linked question because the list was not sorted. Here, we don't have the same problem, and we can use bisect
for the speed it provides:
import bisect
def find_closest_index(a, x):
i = bisect.bisect_left(a, x)
if i >= len(a):
i = len(a) - 1
elif i and a[i] - x > x - a[i - 1]:
i = i - 1
return (i, a[i])
find_closest_index([1, 2, 3, 7, 10, 11], 0) # => 0, 1
find_closest_index([1, 2, 3, 7, 10, 11], 7) # => 3, 7
find_closest_index([1, 2, 3, 7, 10, 11], 8) # => 3, 7
find_closest_index([1, 2, 3, 7, 10, 11], 9) # => 4, 10
find_closest_index([1, 2, 3, 7, 10, 11], 12) # => 5, 11
编辑:如果数组降序:
def bisect_left_rev(a, x, lo=0, hi=None):
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if a[mid] > x: lo = mid+1
else: hi = mid
return lo
def find_closest_index_rev(a, x):
i = bisect_left_rev(a, x)
if i >= len(a):
i = len(a) - 1
elif i and a[i] - x < x - a[i - 1]:
i = i - 1
return (i, a[i])
find_closest_index_rev([11, 10, 7, 3, 2, 1], 0) # => 5, 1
find_closest_index_rev([11, 10, 7, 3, 2, 1], 7) # => 2, 7
find_closest_index_rev([11, 10, 7, 3, 2, 1], 8) # => 2, 7
find_closest_index_rev([11, 10, 7, 3, 2, 1], 9) # => 1, 10
find_closest_index_rev([11, 10, 7, 3, 2, 1], 12) # => 0, 11
这篇关于在已排序的python列表中,找到最接近目标值的值及其在列表中的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文