我需要一个滚动窗口(也称为滑动窗口)可在序列/迭代器/生成器上使用。默认的Python迭代可视为一种特殊情况,其中窗口长度为1。我目前正在使用以下代码。有没有人有一个更蟒蛇,更少冗长,或更有效的方法来做这件事?
def rolling_window(seq, window_size): it = iter(seq) win = [it.next() for cnt in xrange(window_size)] # First window yield win for e in it: # Subsequent windows win[:-1] = win[1:] win[-1] = e yield win if __name__=="__main__": for w in rolling_window(xrange(6), 3): print w """Example output: [0, 1, 2] [1, 2, 3] [2, 3, 4] [3, 4, 5] """
117
Python文档的旧版本中有一个带有itertools示例:
itertools
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
文档中的一个更为简洁,itertools我想它可以起到更大的作用。