在未完全排序的列表中查找最接近值的项目的索引 [英] finding index of an item closest to the value in a list that's not entirely sorted

查看:101
本文介绍了在未完全排序的列表中查找最接近值的项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我的列表是:

[25.75443, 26.7803, 25.79099, 24.17642, 24.3526, 22.79056, 20.84866, 19.49222, 18.38086, 18.0358, 16.57819, 15.71255, 14.79059, 13.64154, 13.09409, 12.18347, 11.33447, 10.32184, 9.544922, 8.813385, 8.181152, 6.983734, 6.048035, 5.505096, 4.65799]

,并且我正在寻找最接近11.5的值的索引.我尝试了其他方法,例如二进制搜索和bisect_left,但是它们不起作用.

and I'm looking for the index of the value closest to 11.5. I've tried other methods such as binary search and bisect_left but they don't work.

我无法对该数组进行排序,因为该值的索引将用于类似的数组上以获取该索引处的值.

I cannot sort this array, because the index of the value will be used on a similar array to fetch the value at that index.

推荐答案

尝试以下操作:

min(range(len(a)), key=lambda i: abs(a[i]-11.5))

例如:

>>> a = [25.75443, 26.7803, 25.79099, 24.17642, 24.3526, 22.79056, 20.84866, 19.49222, 18.38086, 18.0358, 16.57819, 15.71255, 14.79059, 13.64154, 13.09409, 12.18347, 11.33447, 10.32184, 9.544922, 8.813385, 8.181152, 6.983734, 6.048035, 5.505096, 4.65799]
>>> min(range(len(a)), key=lambda i: abs(a[i]-11.5))
16

或者获取索引和值:

>>> min(enumerate(a), key=lambda x: abs(x[1]-11.5))
(16, 11.33447)

这篇关于在未完全排序的列表中查找最接近值的项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆