2
鉴于[1,2,3,4,5,6,7,8,9,10]
,同时获得3项的滑动窗口来获得:跳过滑动窗口
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10)]
从https://stackoverflow.com/q/42220614/610569,可以实现一个序列的滑动窗口:
def per_window(sequence, n=1):
"""
Returns a sliding window.
From https://stackoverflow.com/q/42220614/610569
>>> list(per_window([1,2,3,4], n=2))
[(1, 2), (2, 3), (3, 4)]
>>> list(per_window([1,2,3,4], n=3))
[(1, 2, 3), (2, 3, 4)]
"""
start, stop = 0, n
seq = list(sequence)
while stop <= len(seq):
yield tuple(seq[start:stop])
start += 1
stop += 1
但是,如果有一些限制,我想提出的滑动窗口,而我只是想将某个组件中存在的窗口。
比方说,我只想要一个包含4窗户,我可以是这样的:
>>> [window for window in per_window(x, 3) if 4 in window]
[((2, 3, 4), (3, 4, 5), (4,5,6)]
但透过如果条件莫名其妙环路仍然有通过窗户的整个列表,以处理和检查。
我可以通过查找4
的位置并将输入限制为per_window
(例如,
# Input sequence.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Window size.
n = 3
# Constraint.
c = 4
# Set the index to 0
i = 0
while i < len(x)-n:
i = x.index(4, i)
# First window where the constraint is met.
left = i - (n-1)
if left > 0:
print (list(per_window(x[left:i], 3)))
right = i + n
if right < len(x):
print (list(per_window(x[i:right], 3)))
i = right
(注意上面的代码与IFS不工作=()
相反找到per_window
功能外的索引的,有另一种方法在功能per_window
添加这样的限制?
EDITED
阅读@ RaymondHettinger的回答后:
def skipping_window(sequence, target, n=3):
"""
Return a sliding window with a constraint to check that
target is inside the window.
From https://stackoverflow.com/q/43626525/610569
"""
start, stop = 0, n
seq = list(sequence)
while stop <= len(seq):
subseq = seq[start:stop]
if target in subseq:
yield tuple(seq[start:stop])
start += 1
stop += 1
# Fast forwarding the start.
# Find the next window which contains the target.
try:
# `seq.index(target, start) - (n-1)` would be the next
# window where the constraint is met.
start = max(seq.index(target, start) - (n-1), start)
stop = start + n
except ValueError:
break
[OUT]:
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(skipping_window(x, 4, 3))
[(2, 3, 4), (3, 4, 5), (4, 5, 6)]
但是,这仍然会通过各种可能的窗口循环,只是它不一样,如果它失败的约束,没有屈服? =( – alvas
给出的答案问的问题相匹配。另外,很显然,你已经通过使用*指数()*快速前进到下一个可能匹配的子知道路径进一步优化。 –
谢谢@RaymondHettinger!只需要确认不包括“快进”优化,我在考虑是否遗漏了某些东西=) – alvas