如何在不使用slice,itertools,len()等的情况下使用iter和next实现滚动/滑动窗口? 到目前为止,这就是我所拥有的,但是由于append(next(iterator)),显然这是行不通的。而且我找不到任何好的解决方案。
def windows(iterable,n, m):
while True:
try:
empty_list = []
append = empty_list.append
for i in range(s, e):
append(next(iterator))
yield empty_list
s += m
e += m
check += 1
except StopIteration:
return
我发现此代码完全符合我的要求,但不适用于我的参数。由于我的可迭代参数使用称为伪装的方法,因此:
def disguise(iterable):
for x in iterable:
yield x
我只能将值迭代到列表中,但不允许这样做,“ for for in range(-1,-j-1,-1)”之类的部分也让我很困惑。 Rolling or sliding window iterator?
def window(seq, size, step=1):
# initialize iterators
iters = [iter(seq) for i in range(size)]
# stagger iterators (without yielding)
[next(iters[i]) for j in range(size) for i in range(-1, -j-1, -1)]
while(True):
yield [next(i) for i in iters]
# next line does nothing for step = 1 (skips iterations for step > 1)
[next(i) for i in iters for j in range(step-1)]
有没有更简单的方法来解决这个问题?
期望的结果将是:
[['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g'], ['g', 'h', 'i'], ['i', 'j', 'k']]
通过这样的方法调用:
win(disguise('abcdefghijk'),3,2)
答案 0 :(得分:0)
我认为这可以满足您的要求
def windows(iterable, n, m):
it = iter(iterable)
cur = []
while True:
try:
while len(cur) < n:
cur.append(next(it))
yield tuple(cur)
for _ in range(m):
if cur:
cur.pop(0)
else:
next(it)
except StopIteration:
return
print(list(windows(range(10), 3, 2)))
# [(0, 1, 2), (2, 3, 4), (4, 5, 6), (6, 7, 8)]
print(list(windows(range(10), 2, 3)))
# [(0, 1), (3, 4), (6, 7)]