Juse Pallati
Juse Pallati

Reputation: 41

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.

Upvotes: 1

Views: 245

Answers (5)

scriptlearner
scriptlearner

Reputation: 11

lst= [ 0, 1, 5, 0, 3, 7, 1, 3, 9, 1, 0]
index_list=[2, 5 ,8,11]

index_lst2 = [slice(x -2, x +1) for x in index_list]
returned_list = [lst[index] for index in index_lst2]
print(returned_list)

Upvotes: 0

alani
alani

Reputation: 13079

The indices that you are using in your index_list are not very pythonic to begin with, because they do not comply with the indexing conventions employed by slicing in python.

So let's start by correcting this:

index_list = [index + 1 for index in index_list]

Having done that, we can use slice to obtain the necessary slices. None is used to signify the start or end of the list.

[lst[slice(start, end)] for start, end in zip([None] + index_list,
                                              index_list + [None])]

Upvotes: 1

Tom Wojcik
Tom Wojcik

Reputation: 6189

Not sure if pythonic, but numpy has a built in function for that

import numpy as np

lst = [0, 1, 5, 0, 3, 7, 1, 3, 9, 1, 0]
index_list = [el + 1 for el in [2, 5, 8]]

resp = np.split(lst, index_list, axis=0)

print(resp)

Upvotes: 1

Daweo
Daweo

Reputation: 36640

As you tagged your question with numpy possible answer is:

import numpy as np
lst = [ 0, 1, 5, 0, 3, 7, 1, 3, 9, 1, 0]
index_list = [2, 5 ,8]
index_list = [i+1 for i in index_list]  # in python indices are starting with 0
arrays_list = np.split(lst, index_list)
returned_list = list(map(list,arrays_list))
print(returned_list)

Output:

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

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150785

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]]

Upvotes: 1

Related Questions