A simpler approach would be to enumerate the values of the given list, and then group the index-value pairs by given condition with the help of itertools.groupby
. From there getting the indices is trivial:
from itertools import groupby
cross = [7,5,8,0,0,0,0,2,5,8,0,0,0,0,8,7,9,3,0,0,0,3,2,1,4,5,0,0,0,7,5]
indexed_cross = enumerate(cross) # will yield pairs (0, 7), (1, 5), (2, 8)...
key = lambda x: x[1] > 0 # will give True for pairs with positive second items
indices = []
for key, group in groupby(indexed_cross, key=key):
if key: # True for positive-values groups
chunk = list(group)
indices.append((chunk[0][0], chunk[-1][0])) # extracting the indices
print(indices)
# [(0, 2), (7, 9), (14, 17), (21, 25), (29, 30)]
Alternatively, NumPy can be used for larger arrays:
import bumpy as np
cross = np.array(cross)
padded_values = np.r_[-cross[0], cross, -cross[-1]] # accounting for the first and the last indices
indices = np.where(np.diff(padded_values > 0) != False)[0]
indices = indices.reshape(-1, 2)
indices[:, 1] -= 1
print(indices)
# [[ 0 2]
# [ 7 9]
# [14 17]
# [21 25]
# [29 30]]