I have two lists of numbers
list = [1,2,3,4,5,6,7,8,9]
number = [3,2,1,3]
I want to create index for np.split from number
Approach #1
If we want to use np.split resulting in a list of arrays, we need to use np.cumsum
on those indexes to give us indices where we need to split the input list -
np.split(list1, np.cumsum(number)[:-1])
Sample run -
In [36]: list1 = [1,2,3,4,5,6,7,8,9]
...: number = [3,2,1,3]
...:
In [37]: np.split(list1, np.cumsum(number)[:-1])
Out[37]: [array([1, 2, 3]), array([4, 5]), array([6]), array([7, 8, 9])]
Approach #2
To have a list of lists, another approach with a loop comprehension again using cumsum
-
idx = np.r_[0,np.cumsum(number)]
out = [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
Sample run -
In [45]: idx = np.r_[0,np.cumsum(number)]
In [46]: [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
Out[46]: [[1, 2, 3], [4, 5], [6], [7, 8, 9]]