Split Python list by custom block size based on second list

I am looking for a way to break a list into predefined fragments:

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

The list ashould be cut into len(b)sublists containing the first 200 elements of a, the next 500 and the last 300. We can safely assume that sum(b) == len(a).

Is there a common function for this?

+4
source share
3 answers

Make an iterator from the list (if it is not already one) and get nonce an element nextfrom the iterator for each nin 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]]
+5
source

itertools.islice a :

>>> from itertools import islice
>>> b = [200, 500, 300]
>>> a = range(1, 1001)
>>> it  = iter(a)
>>> [list(islice(it, i)) for i in b]
+3

itertools.islice:

from itertools import islice

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

c = iter(a)
results = [list(islice(c, length)) for length in b]

islicebehaves like a slice, except that the slice accepts the sequence and returns the sequence, while it isliceaccepts iterability and returns iterability.

One-time iterators - as soon as you extract an element from it, it no longer exists, and the next element becomes the new first element.

+3
source

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


All Articles