我有一个字符串列表,我想一次窗口显示它们'n'。每次遇到某个字符串时,窗口都应该重新启动。这是我使用的代码:
i = 0
a = ['Abel', 'Bea', 'Clare', 'Abel', 'Ben', 'Constance', 'Dave', 'Emmet', 'Abel', 'Bice', 'Carol', 'Dennis']
n=3
while i in range(len(a)-n+1):
print('Window :', a[i:i+n])
i += 1
if a[i] == 'Abel':
print()
continue
我得到的输出是:
Window : ['Abel', 'Bea', 'Clare']
Window : ['Bea', 'Clare', 'Abel']
Window : ['Clare', 'Abel', 'Ben']
Window : ['Abel', 'Ben', 'Constance']
Window : ['Ben', 'Constance', 'Dave']
Window : ['Constance', 'Dave', 'Emmet']
Window : ['Dave', 'Emmet', 'Abel']
Window : ['Emmet', 'Abel', 'Bice']
Window : ['Abel', 'Bice', 'Carol']
Window : ['Bice', 'Carol', 'Dennis']
而我希望它在每次"Abel"进入非第一个位置时重新开始窗口化,比如:
#Expected result
Window : ['Abel' , 'Bea', 'Clare']
Window : ['Abel', 'Ben', 'Constance']
Window : ['Ben', 'Constance', 'Dave']
Window : ['Constance', 'Dave', 'Emmet']
Window : ['Abel', 'Bice', 'Carol']
Window : ['Bice', 'Carol', 'Dennis']
我做错了什么?
这是的解决方案
data = [
"Abel",
"Bea",
"Clare",
"Abel",
"Ben",
"Constance",
"Dave",
"Emmet",
"Abel",
"Bice",
"Carol",
"Dennis",
]
data_size = len(data)
window_size = 3
restart_match_value = "Abel"
i = 0
j = 0
while i < data_size - window_size + 1:
window = []
should_restart = False
for j in range(i, i + window_size):
window.append(data[j])
if len(window) > 1 and data[j] == restart_match_value:
should_restart = True
i = j - 1
if should_restart:
print()
else:
print("Window:", window)
i += 1
首先,您不应该检查a[i]
是否为'Abel'
,您应该检查窗口之后的下一个元素是否为Abel,即a[i+n]
。
此外,您应该在检查您的病情后增加i
。
最后,当您遇到'Abel'
时,您应该将迭代器i
增加3,以按预期跳过窗口3个位置。
我希望这能有所帮助:
i = 0
a = ['Abel', 'Bea', 'Clare', 'Abel', 'Ben', 'Constance', 'Dave', 'Emmet', 'Abel', 'Bice', 'Carol', 'Dennis']
n=3
while i in range(len(a)-n+1):
print('Window :', a[i:i+n])
# Notice how I check a[i+n] does not get out of bounds.
if i+n+1 < len(a) and a[i+n] == 'Abel':
print()
i += 3
continue
i += 1