在 Python 中跳过迭代变量的 N 个值的最佳方法是什么?

2022-01-10 00:00:00 python iterator

问题描述

在许多语言中,我们可以这样做:

In many languages we can do something like:

for (int i = 0; i < value; i++)
{
    if (condition)
    {
        i += 10;
    }
}

如何在 Python 中做同样的事情?以下(当然)不起作用:

How can I do the same in Python? The following (of course) does not work:

for i in xrange(value):
    if condition:
        i += 10

我可以这样做:

i = 0
while i < value:
  if condition:
    i += 10
  i += 1

但我想知道在 Python 中是否有更优雅的 (pythonic?) 方法.

but I'm wondering if there is a more elegant (pythonic?) way of doing this in Python.


解决方案

使用继续.

for i in xrange(value):
    if condition:
        continue

如果你想强制你的迭代向前跳过,你必须调用 .next().

If you want to force your iterable to skip forwards, you must call .next().

>>> iterable = iter(xrange(100))
>>> for i in iterable:
...     if i % 10 == 0:
...         [iterable.next() for x in range(10)]
... 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
[61, 62, 63, 64, 65, 66, 67, 68, 69, 70]
[81, 82, 83, 84, 85, 86, 87, 88, 89, 90]

如你所见,这很恶心.

相关文章