问题描述
使用continue。
for i in xrange(value):
if condition:
continue
如果您想强制迭代器向前跳过,则必须致电.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]
解决方法
在许多语言中,我们可以执行以下操作:
for (int i = 0; i < value; i++)
{
if (condition)
{
i += 10;
}
}
如何在Python中做同样的事情?以下(当然)不起作用:
for i in xrange(value):
if condition:
i += 10
我可以做这样的事情:
i = 0
while i < value:
if condition:
i += 10
i += 1
但我想知道是否在Python中有更优雅的方法(pythonic?)。