简体   繁体   English

如何创建滑动窗口生成器python 3.3

[英]How to create a sliding window generator python 3.3

[0, 1, 1, 1, -1, -1, -1, -1, 1]

How do you add this with a sliding window generator of 5? 如何使用5的滑动窗口生成器添加它? So it would be 0 + 1 + 1 + 1 + -1 and then 1 + 1 + 1 + -1 + -1, etc. I am trying to calculate them but i am unable to figure how to move my range every time it counts up to 5. 因此它将是0 + 1 + 1 + 1 + -1,然后是1 + 1 + 1 + -1 + -1,依此类推。我试图计算它们,但我无法弄清楚每次移动范围时如何最多计数5。

    for num in range(len(value)+1):
        print(sum(map(int, value[num-n_day:num])))

Where value is the list and n_day is 5 其中value是列表,n_day是5

Sorry I meant I want to do: 0 对不起,我的意思是我想做:0

0+1 = +1
0+1+1 = +2
0+1+1+1 = +3
0+1+1+1-1 = +2
1+1+1-1-1 = +1
1+1-1-1-1 = -1
1-1-1-1-1 = -3
-1-1-1-1+1 = -3

I would just do this with a slice and a list comprehension: 我只是用切片和列表理解来做到这一点:

>>> value = [0, 1, 1, 1, -1, -1, -1, -1, 1]
>>> n_day = 5
>>> [sum(value[i:max(i-n_day, 0):-1]) for i in range(len(value))]
[0, 1, 2, 3, 2, 1, -1, -3, -3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM