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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With