Rolling or sliding window iterator?

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

    why not

    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return zip(a, b)
    

    It is documented in Python doc . You can easily extend it to wider window.

提交回复
热议问题