Rolling or sliding window iterator?

后端 未结 23 1400
南方客
南方客 2020-11-21 05:23

I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. Default Python iteration can be considered a special case, where the window length

23条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 06:01

    Let's make it lazy!

    from itertools import islice, tee
    
    def window(iterable, size): 
        iterators = tee(iterable, size) 
        iterators = [islice(iterator, i, None) for i, iterator in enumerate(iterators)]  
        yield from zip(*iterators)
    
    list(window(range(5), 3))
    # [(0, 1, 2), (1, 2, 3), (2, 3, 4)]
    

提交回复
热议问题