split a generator/iterable every n items in python (splitEvery)

前端 未结 13 1421
臣服心动
臣服心动 2020-11-27 16:44

I\'m trying to write the Haskel function \'splitEvery\' in Python. Here is it\'s definition:

splitEvery :: Int -> [e] -> [[e]]
    @\'splitEvery\' n@ s         


        
13条回答
  •  误落风尘
    2020-11-27 17:25

    I came across this as I'm trying to chop up batches too, but doing it on a generator from a stream, so most of the solutions here aren't applicable, or don't work in python 3.

    For people still stumbling upon this, here's a general solution using itertools:

    from itertools import islice, chain
    
    def iter_in_slices(iterator, size=None):
        while True:
            slice_iter = islice(iterator, size)
            # If no first object this is how StopIteration is triggered
            peek = next(slice_iter)
            # Put the first object back and return slice
            yield chain([peek], slice_iter)
    

提交回复
热议问题