Rolling or sliding window iterator?

后端 未结 23 1404
南方客
南方客 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 05:55

    I like tee():

    from itertools import tee, izip
    
    def window(iterable, size):
        iters = tee(iterable, size)
        for i in xrange(1, size):
            for each in iters[i:]:
                next(each, None)
        return izip(*iters)
    
    for each in window(xrange(6), 3):
        print list(each)
    

    gives:

    [0, 1, 2]
    [1, 2, 3]
    [2, 3, 4]
    [3, 4, 5]
    

提交回复
热议问题