Python 如何在 for 循环中跳过几次迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17837316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:17:38  来源:igfitidea点击:

How do I skip a few iterations in a for loop

pythonloops

提问by Alex S

In python I usually loop through ranges simply by

在python中,我通常简单地循环遍历范围

for i in range(100): 
    #do something

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.

但现在我想跳过循环中的几个步骤。更具体地说,我想要类似的东西,continue(10)这样它就可以跳过整个循环并将计数器增加 10。如果我在 C 中使用 for 循环,我只会将 10 与 相加i,但在 Python 中这并没有真正起作用。

采纳答案by Martijn Pieters

You cannot alter the target list (iin this case) of a forloop. Use a whileloop instead:

您不能更改循环的目标列表(i在本例中)for。改用while循环:

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

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 itertoolsconsume recipe). fornormally calls iter()for us when looping over a iterator.

通过将 的结果分配给iter()局部变量,我们可以使用标准迭代工具(next(),或者这里是itertools消耗配方的缩短版本)推进循环内的循环序列。for通常iter()在循环迭代器时调用我们。

回答by Gareth Latty

The best way is to assign the iterator a name - it is common have an iterable as opposed to an iterator (the difference being an iterable - for example a list - starts from the beginning each time you iterate over it). In this case, just use the iter()built-in function:

最好的方法是为迭代器分配一个名称——通常有一个迭代器而不是迭代器(区别在于迭代器——例如列表——每次迭代时从头开始)。在这种情况下,只使用iter()内置函数

numbers = iter(range(100))

Then you can advance it inside the loop using the name. The best way to do this is with the itertoolsconsume()recipe- as it is fast (it uses itertoolsfunctions to ensure the iteration happens in low-level code, making the process of consuming the values very fast, and avoids using up memory by storing the consumed values):

然后您可以使用名称在循环内推进它。要做到这一点,最好的办法是itertoolsconsume()配方-因为它是快(其使用itertools功能,以确保迭代发生在低级别的代码,使得速度非常快消耗值的过程,并避免使用内存的存储消耗值):

from itertools import islice
import collections

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

By doing this, you can do something like:

通过这样做,您可以执行以下操作:

numbers = iter(range(100))
for i in numbers: 
    ...
    if some_check(i):
        consume(numbers, 3)  # Skip 3 ahead.

回答by Josh Buell

Why not just set the value to skip until? Like:

为什么不将值设置为跳过直到?喜欢:

skip_until = 0
for i in range(100):
    if i < skip_until:
        continue
    if SOME_CONDITION:
        skip_until = i + 10
    DO_SOMETHING()

where SOME_CONDITION is whatever causes you to skip and DO_SOMETHING() is the actual loop contents?

其中 SOME_CONDITION 是导致您跳过的原因,而 DO_SOMETHING() 是实际的循环内容?

回答by Jonathan

for i in range(0, 100, 10):
    print(i)

will print 0, 10, 20 ...

将打印 0, 10, 20 ...