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?
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]]
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