What would be the most Pythonic way to find the first index in a list that is greater than x?
For example, with
list = [0.5, 0.3, 0.9, 0.8]
for index, elem in enumerate(elements):
if elem > reference:
return index
raise ValueError("Nothing Found")
Try this one:
def Renumerate(l):
return [(len(l) - x, y) for x,y in enumerate(l)]
example code:
Renumerate(range(10))
output:
(10, 0)
(9, 1)
(8, 2)
(7, 3)
(6, 4)
(5, 5)
(4, 6)
(3, 7)
(2, 8)
(1, 9)
>>> alist= [0.5, 0.3, 0.9, 0.8]
>>> [ n for n,i in enumerate(alist) if i>0.7 ][0]
2
You could also do this using numpy
:
import numpy as np
list(np.array(SearchList) > x).index(True)
1) NUMPY SOLUTION, general lists
If you are happy to use numpy, then the following will work on general lists (sorted or unsorted):
numpy.argwhere(np.array(searchlist)>x)[0]
or if you need the answer as a list:
numpy.argwhere(np.array(searchlist)>x).tolist()[0]
or if you need the answer as a integer index:
numpy.argwhere(np.array(searchlist)>x).tolist()[0][0]
2) NUMPY SOLUTION, sorted lists
However, if your search list is sorted, it is much cleaner and nicer to use the function np.searchsorted:
numpy.searchsorted(searchlist,x)
The nice thing about using this function is that as well as search for a single value x, you can also return a list of indices for a list of values x, (and it is very efficient relative to a list comprehension in this case).
Another one:
map(lambda x: x>.7, seq).index(True)