Rolling or sliding window iterator?

后端 未结 23 1478
南方客
南方客 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:52

    Modified DiPaolo's answer to allow arbitrary fill and variable step size

    import itertools
    def window(seq, n=2,step=1,fill=None,keep=0):
        "Returns a sliding window (of width n) over data from the iterable"
        "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
        it = iter(seq)
        result = tuple(itertools.islice(it, n))    
        if len(result) == n:
            yield result
        while True:        
    #         for elem in it:        
            elem = tuple( next(it, fill) for _ in range(step))
            result = result[step:] + elem        
            if elem[-1] is fill:
                if keep:
                    yield result
                break
            yield result
    

提交回复
热议问题