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

前端 未结 13 1317
臣服心动
臣服心动 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:48

    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
    
    0 讨论(0)
提交回复
热议问题