Rolling or sliding window iterator?

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

    There's one in an old version of the Python docs with itertools examples:

    from itertools import islice
    
    def window(seq, n=2):
        "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(islice(it, n))
        if len(result) == n:
            yield result
        for elem in it:
            result = result[1:] + (elem,)
            yield result
    

    The one from the docs is a little more succinct and uses itertools to greater effect I imagine.

提交回复
热议问题