Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list into sublists based on a set of indexes in Python

Tags:

python

I have a list similar to below

['a','b','c','d','e','f','g','h','i','j']

and I would like to separate by a list of index

[1,4]

In this case, it will be

[['a'],['b','c'],['d','e','f','g','h','i','j']]

As

[:1] =['a']

[1:4] = ['b','c']

[4:] = ['d','e','f','g','h','i','j']

Case 2: if the list of index is

[0,6]

It will be

[[],['a','b','c','d','e'],['f','g','h','i','j']]

As

[:0] = []

[0:6] = ['a','b','c','d','e']

[6:] = ['f','g','h','i','j']

Case 3 if the index is

[2,5,7]

it will be [['a','b'],['c','d','e'],['h','i','j']] As

[:2] =['a','b']
[2:5] = ['c','d','e']
[5:7] = ['f','g']
[7:] = ['h','i','j']
like image 835
Platalea Minor Avatar asked Jan 26 '23 10:01

Platalea Minor


2 Answers

Something along these lines:

mylist = ['a','b','c','d','e','f','g','h','i','j']
myindex = [1,4]

[mylist[s:e] for s, e in zip([0]+myindex, myindex+[None])]

Output

[['a'], ['b', 'c', 'd'], ['e', 'f', 'g', 'h', 'i', 'j']]
like image 73
Fourier Avatar answered Jan 31 '23 22:01

Fourier


This solution is using numpy:

import numpy as np

def do_split(lst, slices):
    return [sl.tolist()for sl in np.split(lst, slices)]

splits = do_split(a, [2,5,7])

Out[49]:
[['a', 'b'], ['c', 'd', 'e'], ['f', 'g'], ['h', 'i', 'j']]

like image 41
cristian hantig Avatar answered Jan 31 '23 22:01

cristian hantig