Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding index of an item closest to the value in a list that's not entirely sorted

As an example my list is:

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

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.

like image 532
emad Avatar asked Mar 14 '12 16:03

emad


People also ask

How do you find the index of an element in a list of lists?

By using the list. index() method, we can easily get the element index value from list. In this example we have define a list of integer values and uses the list. index() method we can get the index of the item whose value is '210'.

How do I find the index of a specific element?

ArrayList. indexOf(). This method returns the index of the first occurance of the element that is specified. If the element is not available in the ArrayList, then this method returns -1.


2 Answers

Try the following:

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

For example:

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

Or to get the index and the value:

>>> min(enumerate(a), key=lambda x: abs(x[1]-11.5)) (16, 11.33447) 
like image 69
Andrew Clark Avatar answered Oct 17 '22 15:10

Andrew Clark


import numpy as np  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]  index = np.argmin(np.abs(np.array(a)-11.5)) a[index] # here is your result 

In case a is already an array, the corresponding transformation can be ommitted.

like image 30
Carsten König Avatar answered Oct 17 '22 14:10

Carsten König