1

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.

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
  • Does this answer your question? [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – Rafa Acioly Aug 05 '20 at 13:22

5 Answers5

1

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]]
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
1

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])]
alani
  • 12,573
  • 2
  • 13
  • 23
1

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]]
Daweo
  • 31,313
  • 3
  • 12
  • 25
1

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)

Tom Wojcik
  • 5,471
  • 4
  • 32
  • 44
0
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)
alani
  • 12,573
  • 2
  • 13
  • 23
  • 1
    Your answer works (for this example - not sure it does in the general case), but it looks like you could use some help with the markup. A code block is started and finished by a line of three backticks. I'll edit your answer on this occasion to add it. – alani Aug 05 '20 at 14:02