Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Python list into custom chunk size based on second list

Tags:

python

list

slice

I am looking for a way to split a list into predefined slices:

a = list(range(1, 1001)) # Added list() 
b = [200, 500, 300]

List a should be sliced into len(b) sublists containing the first 200 elements of a, the following 500, and the last 300. It is safe to assume that sum(b) == len(a).

Is there a common function for this?

like image 584
Matthias Avatar asked Dec 19 '22 15:12

Matthias


1 Answers

Make an iterator from the list (if it isn't one already) and get n times the next element from the iterator for each n in b.

>>> a = range(1, 1001)
>>> b = [200, 500, 300]
>>> a_iter = iter(a)
>>> [[next(a_iter) for _ in range(n)] for n in b]
[[1,
  2,
  ...
  199,
  200],
 [201,
  ...
  700],
 [701,
  702,
  ...
  999,
  1000]]
like image 188
tobias_k Avatar answered Dec 21 '22 11:12

tobias_k