Here is a one-linear Numpythonic approach:
np.split(arr, np.where(np.diff(arr) < 0)[0] + 1)
Or a similar approach to numpy code but less efficient:
from operator import sub
from itertools import starmap
indices = [0] + [
i+1 for i, j in enumerate(list(
starmap(sub, zip(num_list[1:], num_list)))
) if j < 0] + [len(num_list)
] + [len(num_list)]
result = [num_list[i:j] for i, j in zip(indices, indices[1:])]
Demo:
# Numpy
In [8]: np.split(num_list, np.where(np.diff(num_list) < 0)[0] + 1)
Out[8]:
[array([ 97, 122]),
array([99]),
array([ 98, 111, 112, 113]),
array([100, 102])]
# Python
In [42]: from operator import sub
In [43]: from itertools import starmap
In [44]: indices = [0] + [i+1 for i, j in enumerate(list(starmap(sub, zip(num_list[1:], num_list)))) if j < 0] + [len(num_list)]
In [45]: [num_list[i:j] for i, j in zip(indices, indices[1:])]
Out[45]: [[97, 122], [99], [98, 111, 112, 113], [100, 102]]
Explanation:
Using np.diff()
you can get the differences of each item with their next item (up until the last element). Then you can use the vectorized nature of numpy to get the indices of the places where this difference is negative, which can be done with a simple comparison and np.where()
. Finally you can simply pass the indices to np.split()
to split the array based on those indices.