I am trying to divide a list of elements which are comma separated into chunks of unequal length. How can I divide it?
list1 = [1, 2, 1]
list2 = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]
list1 contains the elements which are the sizes of chunks which I wish to divide the list2 in.
Something like:
You can also use the
.pop()
method like this:This will modify the original list2.
You could combine the power of
itertools.accumulate
and list comprehensions:itertools.accumulate
returns an iterator to a sequence of accumulated sums. This way you could easily calculate the end of each chunk in the source array:You can use
itertools.islice
for this too. It's efficient and easy to read:Then to use it:
Or as a generator:
In use:
This is also implemented in
more-itertools.split_at
. See here for their source code which is almost identical minus allowing no chunks to be provided which is weird.Yet another solution