Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Split list into sublists based on the first element in the sublists

I want to split a list that looks something like this:

list = [5, a, b, c, d, e, 2, a, b, 4, a ,b ,c ,d , ...]

into this:

list  = [ [5, a, b, c, d, e], [2, a, b] , [4, a ,b ,c ,d] ...]

The first element/number is variable, so no pattern to split it in even chunks. The chunks size or length should be based on that first element of the chunk. Also the alphabetic letters are just placeholders to make the example more readable, in reality the alphabetic letters are floats and numbers.

So the big list really looks something like this:

list = [5, 7, 3.2, 3.1, 4.6, 3, 2, 5.1, 7.1, 4, 5.12 ,3.4 ,4.8 ,12.1 , ...]
like image 274
Mich_Lloid Avatar asked Oct 16 '25 23:10

Mich_Lloid


2 Answers

Simple way, read each chunk length n and include the next n values:

it = iter(l)
[[n, *islice(it, n)] for n in it]

Python 2 version:

it = iter(l)
[[n] + list(islice(it, n)) for n in it]

Or without islice:

it = iter(l)
[[n] + [next(it) for _ in range(n)] for n in it]

Demo:

>>> from itertools import islice
>>> l = [5, 'a', 'b', 'c', 'd', 'e', 2, 'f', 'g', 4, 'h' ,'i' ,'j' ,'k']
>>> it = iter(l)
>>> [[n, *islice(it, n)] for n in it]
[[5, 'a', 'b', 'c', 'd', 'e'], [2, 'f', 'g'], [4, 'h', 'i', 'j', 'k']]
like image 97
Stefan Pochmann Avatar answered Oct 18 '25 15:10

Stefan Pochmann


You can try this one:

l = [5, 'a', 'b', 'c', 'd', 'e', 2, 'a', 'b', 4, 'a' ,'b' ,'c' ,'d']

pos = [(index, i) for index, i in enumerate(l) if type(i)==int]
l = [l[p[0]:p[0]+p[1]+1] for p in pos]
print(l)

Output:

[[5, 'a', 'b', 'c', 'd', 'e'], [2, 'a', 'b'], [4, 'a', 'b', 'c', 'd']]
like image 32
Vasilis G. Avatar answered Oct 18 '25 15:10

Vasilis G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!