I\'m trying to write the Haskel function \'splitEvery\' in Python. Here is it\'s definition:
splitEvery :: Int -> [e] -> [[e]]
@\'splitEvery\' n@ s
Here's a quick one-liner version. Like Haskell's, it is lazy.
from itertools import islice, takewhile, repeat
split_every = (lambda n, it:
takewhile(bool, (list(islice(it, n)) for _ in repeat(None))))
This requires that you use iter before calling split_every.
Example:
list(split_every(5, iter(xrange(9))))
[[0, 1, 2, 3, 4], [5, 6, 7, 8]]
Although not a one-liner, the version below doesn't require that you call iter which can be a common pitfall.
from itertools import islice, takewhile, repeat
def split_every(n, iterable):
"""
Slice an iterable into chunks of n elements
:type n: int
:type iterable: Iterable
:rtype: Iterator
"""
iterator = iter(iterable)
return takewhile(bool, (list(islice(iterator, n)) for _ in repeat(None)))
(Thanks to @eli-korvigo for improvements.)