I have a list, let's say:
list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]
I would like to find the minimum and maximum indices of this list where list_A > 0
, i.e. in the above example, it would be 3 and 7.
For other lists, which increase monotonically, I have been using np.searchsorted
, like np.searchsorted(list,[0.5,1.0])
to find the indices wherein the list is between 0.5 and 1.0
respectively.
But this case is quite different and the np.searchsorted
doesn't work here, or maybe it does in a way which I don't know !
Filter the zipped list with its indixes and take the min and the max:
>>> list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]
>>> filtered_lst = [(x,y) for x,y in enumerate(list_A) if y > 0]
>>> max(filtered_lst)
(7, 1.0)
>>> min(filtered_lst)
(3, 1.0)
If you just need the index, unpack the returned value:
>>> maX,_ = max(filtered_lst)
>>> maX
7