You can use itertools.islice
for this too. It's efficient and easy to read:
def unequal_divide(iterable, chunks):
it = iter(iterable)
return [list(islice(it, c)) for c in chunks]
Then to use it:
>>> list1 = [1, 2, 1]
>>> list2 = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]
>>> unequal_divide(list1, list2)
[['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
Or as a generator:
def unequal_divide(iterable, chunks):
it = iter(iterable)
for c in chunks:
yield list(islice(it, c))
In use:
>>> list(unequal_divide(list1, list2))
[['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
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.