Reputation: 75
I have a sorted list(it contains more than 1000 cumulative elements). For example:
list = [1.236, 2.236, 5.1254, 9.125663, 9.9632, 15.1266, 18.254, 19.3315, 23.3265]
And I have a target number which is let's say 9.5
. I want to find its position in list. So I want to see index 3rd and 4
(it should be between 3 (9.125663) and 4th (9.9632) indexes) as output without using a for loop.
Do you have an idea about it? Thank you.
Upvotes: 2
Views: 100
Reputation: 18306
There is bisect
module for this:
import bisect
the_list = [1.236, 2.236, 5.1254, 9.125663, 9.9632, 15.1266, 18.254, 19.3315, 23.3265]
val = 9.5
pos = bisect.bisect(the_list, val)
to get
>>> pos
4
You can then use (pos-1, pos)
as (3, 4)
(might need to check edge cases).
(Side note: bisect.bisect
is synonymous to bisect.bisect_right
so the returned pos
will be right to the val
if it is already in the list, e.g. if val
was 5.1254
, pos
would be 3).
Upvotes: 3
Reputation: 2248
Used this link for the answer:
import numpy as np
def get_indices(array, value):
array = np.array(array)
# Subtract all values in array with value and get index of smallest value which would be the closest value
idx = (np.abs(array - value)).argmin()
#if closest value is greater than target value
if(array[idx] > value):
#+1 because you want "3rd and 4th" index, and python starts from 0
print([idx+1, idx+2])
#if closest value is lesser than target value
elif(array[idx] < value):
print([idx, idx+1])
else:
print([idx+1])
array = [1.236, 2.236, 5.1254, 9.125663, 9.9632, 15.1266, 18.254, 19.3315, 23.3265]
value = 9.5
get_indices(array, 9.5) ## prints [3,4]
get_indices(array, 10.5) ## prints [4,5]
Upvotes: 2