I\'m trying to write the Haskel function \'splitEvery\' in Python. Here is it\'s definition:
splitEvery :: Int -> [e] -> [[e]]
@\'splitEvery\' n@ s
building off of the accepted answer and employing a lesser-known use of iter
(that, when passed a second arg, it calls the first until it receives the second), you can do this really easily:
python3:
from itertools import islice
def split_every(n, iterable):
iterable = iter(iterable)
yield from iter(lambda: list(islice(iterable, n)), [])
python2:
def split_every(n, iterable):
iterable = iter(iterable)
for chunk in iter(lambda: list(islice(iterable, n)), []):
yield chunk