Rolling or sliding window iterator?

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

    How about using the following:

    mylist = [1, 2, 3, 4, 5, 6, 7]
    
    def sliding_window(l, window_size=2):
        if window_size > len(l):
            raise ValueError("Window size must be smaller or equal to the number of elements in the list.")
    
        t = []
        for i in xrange(0, window_size):
            t.append(l[i:])
    
        return zip(*t)
    
    print sliding_window(mylist, 3)
    

    Output:

    [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]
    

提交回复
热议问题