滑动窗口迭代技术
对于可迭代对象上的滑动窗口迭代,基本实现可以使用列表切片和迭代:
def rolling_window(seq, window_size): it = iter(seq) win = [it.next() for cnt in range(window_size)] # First window yield win for e in it: # Subsequent windows win[:-1] = win[1:] win[-1] = e yield win
高效优雅解决方案
为了提高效率和优雅性,可以使用带有 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
对于列表或元组等更简单的可迭代对象,可以使用使用范围和索引的简单方法使用:
seq = [0, 1, 2, 3, 4, 5] window_size = 3 for i in range(len(seq) - window_size + 1): print(seq[i: i + window_size])
以上是如何在Python中高效实现滑动窗口迭代?的详细内容。更多信息请关注PHP中文网其他相关文章!