Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list into chunks of varying length

Given a sequence of items and another sequence of chunk lengths, how can I split the sequence into chunks of the required lengths?

a = range(10)
l = [3, 5, 2]
split_lengths(a, l) == [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]

Ideally a solution would work with both a and l as general iterables, not just on lists.

like image 237
ecatmur Avatar asked Dec 04 '22 13:12

ecatmur


1 Answers

Use itertools.islice on an iterator of the list.

In [12]: a = range(10)

In [13]: b = iter(a)

In [14]: from itertools import islice

In [15]: l = [3, 5, 2]

In [16]: [list(islice(b, x)) for x in l]
Out[16]: [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]

or :

In [17]: b = iter(a)

In [18]: [[next(b) for _ in range(x)] for x in l]
Out[18]: [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]
like image 88
Ashwini Chaudhary Avatar answered Dec 18 '22 14:12

Ashwini Chaudhary