简体   繁体   English

可变增量的滑动窗口-Python

[英]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. 我正在尝试在Python中使用滑动窗口函数来比较很长的值列表。 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 len(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? 我的问题是,如何修改此代码,以便可以将窗口的增量(每个元组生成后窗口的移动量)从1更改为更大的整数,例如5或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: 您不必更改增量,可以使用第n个元素:

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

Not fully optimized, but simple. 尚未完全优化,但很简单。

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

Hint: the next function can be used to obtain the next element from the iterator. 提示: next函数可用于从迭代器获取next元素。 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 :) ). 您需要在每次迭代中获取并添加多个元素(我想这就是难题;您肯定会看到如何将窗口的另一端向前移动不同的量:))。

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

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