开发者

Sliding Window with Variable Increment - Python

I am trying to use the sliding window function in Python to compare a very long list of values. The code I have found for the sliding window function is below:

from itertools import islice

idlist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list = []

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 l开发者_Python百科en(result) == n:
        yield result    
    for elem in it:
        result = result[1:] + (elem,)
        yield result

for i in window(idlist, n=2):
    list.append(i)

print list

My question is, how would I modify this code so I could change the increment of the window (the amount it moves after each tuple is generated) from 1 to a much greater integer, say 5 or 50? I know how to change the size of the window, but not the increment. Thanks!


You don't have to change the increment, you can take every n'th element:

# taking every 3rd element moves the start by 3
print list(islice(window(idlist, n=2),None,None,3))

Not fully optimized, but simple.


Hint: the next function can be used to obtain the next element from the iterator. You need to obtain and append multiple elements per iteration (I assume that's the difficulty; surely you see how to move the other end of the window forward a different amount :) ).


maybe this solve the problem

L=[1,2,3,4,5]

def window(L, n=2, jump=1):
    lenght = len(L)
    assert n <= lenght
    for i in range(0,lenght-n+1,jump):
        yield tuple(L[i:i+n])

A=[]
for i in window(L, n=3, jump=1):
    A.append(i)

print A
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜