python排序返回索引号,在已排序的python列表中,找到最接近目标值的值及其在列表中的索引...

该博客介绍了如何在Python中实现类似于MATLAB的查找有序列表中与目标值最接近的元素及其索引的功能。利用`bisect`模块提高效率,提供了升序和降序列表的解决方案,并给出了多个示例来展示其用法。
摘要由CSDN通过智能技术生成

I am trying to get both the closest value and its index in a sorted list in python.

In MATLAB this is possible with:

[closest_val,index] = min(abs(array - target))

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 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

EDIT: In case of descending array:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值