Split the list into pieces of different lengths

Given a sequence of elements and another sequence of block lengths, how can I split a sequence into pieces of the required length?

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

Ideally, the solution will work with both a and l as general iterations, not just lists.

+4
source share
2 answers

Use itertools.islice on a list iterator.

 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]] 
+14
source
 def split_lengths(a,l): resultList = [] index=0 for length in l: resultList.append(a[index : index + length]) index = index + length retun resultList 
0
source

Source: https://habr.com/ru/post/1446440/


All Articles