简体   繁体   中英

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? 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.

    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

Sorry I meant I want to do: 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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