跳过枚举列表对象中的迭代(python) [英] Skip iterations in enumerated list object (python)

查看:64
本文介绍了跳过枚举列表对象中的迭代(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有验证码

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

如您所见,我希望在满足条件的情况下让for循环跳过5次迭代.我可以肯定的是,如果满足条件,则行"对象中还剩下5个或更多对象.

I would like, as you can read, have the for loop skip 5 iterations if the condition is met. I can be sure that, if the condition is met, there are 5 or more objects left in the "lines" object.

行包含一系列字典,这些字典必须按顺序循环

lines exists of an array of dictionaries, which have to be looped over in order

推荐答案

iline = 0
while iline < len(lines):
    line = lines[iline]
    if <condition>:
        place_where_skip_happened = iline
        iline += 5
    iline += 1

如果要遍历文件对象,则可以使用next跳过行或将行设置为迭代器:

If you are iterating over a file object you can skip lines using next or make lines an iterator:

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

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

It really depends on what you are iterating over and what you want to do.

通过 iter 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆