Rolling or sliding window iterator?

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

    Trying my part, simple, one liner, pythonic way using islice. But, may not be optimally efficient.

    from itertools import islice
    array = range(0, 10)
    window_size = 4
    map(lambda i: list(islice(array, i, i + window_size)), range(0, len(array) - window_size + 1))
    # output = [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9]]
    

    Explanation: Create window by using islice of window_size and iterate this operation using map over all array.

提交回复
热议问题