7

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 !

Georgy
  • 12,464
  • 7
  • 65
  • 73
Srivatsan
  • 9,225
  • 13
  • 58
  • 83
  • This is duplicated http://stackoverflow.com/questions/7270321/finding-the-index-of-elements-based-on-a-condition-using-python-list-comprehensi (don't know how to mark it as so) – tglaria Jan 07 '16 at 12:46

3 Answers3

6

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
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • Your solution is really simply. But what I need is just the index, not the value (i.e. 1.0). `filtered_list[0]` doesn't work ? – Srivatsan Jan 07 '16 at 11:19
2

An alternative would be to use next():

list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]

print(next(idx for idx, item in enumerate(list_A) if item>0))
print(next(len(list_A)-1-idx for idx, item in enumerate(list_A[::-1]) if item>0))

Output

3
7

Using next() to find the first item in the list > 0 is an elegant solution.

To find the last item in the list > 0 is trickier with this method. I use next() to iterate over and find the first item > 0 in the reversed list using list_A[::-1]. I then convert the index generated to the correct index by subtracting it from len(list)-1, using len(list)-1-idx .

gtlambert
  • 11,711
  • 2
  • 30
  • 48
1

You can use the np.where function to return indices of all elements > 0

In [116]: list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]

In [117]: arr = np.array(list_A)

In [118]: indx = np.where(arr > 0)[0]

In [119]: mini = indx[0]

In [120]: mini
Out[120]: 3

In [121]: maxi = indx[-1]

In [122]: maxi
Out[122]: 7
styvane
  • 59,869
  • 19
  • 150
  • 156