我如何跳过for循环中的一些迭代 [英] How do I skip a few iterations in a for loop

查看:122
本文介绍了我如何跳过for循环中的一些迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,我通常通过

In python I usually loop through ranges simply by

for i in range(100): 
    #do something

但是现在我想跳过循环中的一些步骤.更具体地说,我想要类似continue(10)的内容,这样它将跳过整个循环并将计数器增加10.如果我在C中使用for循环,我只会将10加到i,但是在Python中不会真的不行.

but now I want to skip a few steps in the loop. More specifically, I want something like continue(10) so that it would skip the whole loop and increase the counter by 10. If I were using a for loop in C I'd just sum 10 to i, but in Python that doesn't really work.

推荐答案

您不能更改for循环的目标列表(在这种情况下为i).请使用while循环:

You cannot alter the target list (i in this case) of a for loop. Use a while loop instead:

while i < 10:
    i += 1
    if i == 2:
        i += 3

或者,使用可迭代的增量:

Alternatively, use an iterable and increment that:

from itertools import islice

numbers = iter(range(10))
for i in numbers:
    if i == 2:
        next(islice(numbers, 3, 3), None)  # consume 3

通过将iter()的结果分配给局部变量,我们可以使用标准迭代工具(next()或此处为itertools消耗配方的简化版本)在循环内部推进循环序列. for通常在遍历迭代器时为我们调用iter().

By assigning the result of iter() to a local variable, we can advance the loop sequence inside the loop using standard iteration tools (next(), or here, a shortened version of the itertools consume recipe). for normally calls iter() for us when looping over a iterator.

这篇关于我如何跳过for循环中的一些迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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