可变增量滑动窗口 - Python
我正在尝试使用Python中的滑动窗口函数来比较很长的值列表。我找到的滑动窗口函数的代码如下:
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
我的问题是,如何修改此代码,以便将窗口的增量(生成每个元组后移动的量)从 1 更改为更大的整数,说5还是50?我知道如何更改窗口的大小,但不知道增量。 谢谢!
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 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? I know how to change the size of the window, but not the increment.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不必更改增量,您可以获取每个第 n 个元素:
未完全优化,但很简单。
You don't have to change the increment, you can take every n'th element:
Not fully optimized, but simple.
提示:
next
函数可用于从迭代器获取下一个元素。您需要在每次迭代中获取并附加多个元素(我认为这就是困难;您肯定知道如何将窗口的另一端向前移动不同的量:))。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