我有代码

for iline, line in enumerate(lines):
    ...
    if <condition>:
        <skip 5 iterations>

如您所见,我想在满足条件的情况下让for循环跳过5次迭代。我可以确定,如果满足条件,则“行”对象中还剩下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

这实际上取决于您要迭代的内容和要执行的操作。

iterislice使用您自己的代码:
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/

10-11 22:03