我有密码
for iline, line in enumerate(lines):
...
if <condition>:
<skip 5 iterations>
如您所见,如果满足条件,我希望 for 循环跳过 5 次迭代。我可以确定,如果满足条件,则“lines”对象中还剩下 5 个或更多对象。
存在字典数组的行,必须按顺序循环
最佳答案
iline = 0
while iline < len(lines):
line = lines[iline]
if <condition>:
place_where_skip_happened = iline
iline += 5
iline += 1
如果您正在遍历一个文件对象,您可以使用 next 跳过行或使行成为迭代器:
lines = iter(range(20))
for l in lines:
if l == 10:
[next(lines) for _ in range(5)]
print(l)
0
1
2
3
4
5
6
7
8
9
10
16
17
18
19
这实际上取决于您要迭代的内容以及您想要执行的操作。
from itertools import islice
it = iter(enumerate(lines))
for iline, line in it:
if <condition>:
place_where_skip_happened = iline
next(islice(it,5 ,5), None)
print(line)
关于python - 跳过枚举列表对象中的迭代(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28138392/