相关疑难解决方法(0)

滚动或滑动窗口迭代器?

我需要一个可在序列/迭代器/生成器上迭代的滚动窗口(也称为滑动窗口).默认的Python迭代可以被认为是一种特殊情况,窗口长度为1.我目前正在使用以下代码.有没有人有更多的Pythonic,更简洁,或更有效的方法来做到这一点?

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]
"""
Run Code Online (Sandbox Code Playgroud)

python algorithm

142
推荐指数
10
解决办法
8万
查看次数

在Python中将列表迭代为对(当前,下一个)

我有时需要在Python中迭代一个列表,查看"current"元素和"next"元素.到目前为止,我已经完成了以下代码:

for current, next in zip(the_list, the_list[1:]):
    # Do something
Run Code Online (Sandbox Code Playgroud)

这有效并且符合我的预期,但是有更多惯用或有效的方法来做同样的事情吗?

python

121
推荐指数
7
解决办法
4万
查看次数

标签 统计

python ×2

algorithm ×1