滚动窗口迭代器还是滑动窗口迭代器?我需要一个滚动窗口(也称滑动窗口),可以在序列/迭代器/生成器上迭代。默认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 winif __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]
"""
4 回答
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
itertools
from itertools import islicedef 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
慕容森
TA贡献1853条经验 获得超18个赞
collections.deque
list
pop(0)
append()
from collections import dequedef window(seq, n=2): it = iter(seq) win = deque((next(it, None) for _ in xrange(n)), maxlen=n) yield win append = win.append for e in it: append(e) yield win
tee
deque
deque
sum(w)
tee
tee
蝴蝶不菲
TA贡献1810条经验 获得超4个赞
tee()
:
from itertools import tee, izipdef window(iterable, size): iters = tee(iterable, size) for i in xrange(1, size): for each in iters[i:]: next(each, None) return izip(*iters)for each in window(xrange(6), 3): print list(each)
[0, 1, 2][1, 2, 3][2, 3, 4][3, 4, 5]
添加回答
举报
0/150
提交
取消