滑動視窗迭代技術
對於可迭代物件上的滑動視窗迭代,基本實作可以使用列表切片和迭代:
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中文網其他相關文章!