NOTE: As suggested by some people, I reposted this question to the codereview site
I want to split a list using another list which contains the lengths of each split.
Eg.
>>> print list(split_by_lengths(list('abcdefg'), [2,1]))
... [['a', 'b'], ['c'], ['d', 'e', 'f', 'g']]
>>> print list(split_by_lengths(list('abcdefg'), [2,2]))
... [['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]
>>> print list(split_by_lengths(list('abcdefg'), [2,2,6]))
... [['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]
>>> print list(split_by_lengths(list('abcdefg'), [1,10]))
... [['a'], ['b', 'c', 'd', 'e', 'f', 'g']]
>>> print list(split_by_lengths(list('abcdefg'), [2,2,6,5]))
... [['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]
As you can notice, if the lengths list does not cover all the list I append the remaining elements as an additional sublist. Also, I want to avoid empty lists at the end in the cases that the lengths list produces more elements that are in the list to split.
I already have a function that works as I want:
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(islice(iterable, n))
def split_by_lengths(list_, lens):
li = iter(list_)
for l in lens:
elems = take(l,li)
if not elems:
break
yield elems
else:
remaining = list(li)
if remaining:
yield remaining
But I wonder if there is a more pythonic way to write a function such that one.
Note: I grabbed take(n, iterable)
from Itertools Recipes: