python广告牌滚动_滚动或在Python滑动窗口迭代器

I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. Default Python iteration can be considered a special case, where the window length is 1. I'm currently using the following code. Does anyone have a more Pythonic, less verbose, or more efficient method for doing this?

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]

"""

解决方案

There's one in an old version of the Python docs with itertools examples:

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

The one from the docs is a little more succinct and uses itertools to greater effect I imagine.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值