Search code examples
pythonlistnumpysublist

Pythonic way to create sublists from a list of indices


I would like to know an elegant way to create smaller lists from a list with indexes in this way:

My list:

 lst= [ 0, 1, 5, 0, 3, 7, 1, 3, 9, 1, 0]

My indexes:

index_list=[2, 5 ,8]

I got the indexes by finding the peaks, now I would like it to create sub lists between these peaks.

So I expect this in return:

returned_list = [[0,1,5], [0,3,7], [1,3,9], [1, 0]]

I am trying something like this:

def sublist(lst, index):

tmplst = []
list_of_list = []


for j in range(len(index)):
    for i in range(len(lst)):
        if index[j] > lst[i]:
            tmplst.append(lst[i])

Please let me know what I can do.


Solution

  • Let's try zip with list comprehension:

    [a[x+1:y+1] for x,y in zip([-1] + index_list, index_list + [len(a)])]
    

    Output:

    [[0, 1, 5], [0, 3, 7], [1, 3, 9], [1, 0]]