如何根据if条件在for循环中跳过几次迭代?

use*_*_12 2 python python-3.x

我有一个 for 循环,我正在寻找一种方法,只要满足该条件就可以跳过几次迭代。我怎样才能在python中做到这一点?

这是第一次满足条件时的示例,

for i in range(0, 200000):
    # (when 0 % 300 it meets this criteria) 
    if (i % 300) == 0:             
        # whenever this condition is met skip 4 iterations forward
        # now skip 4 iterations --- > (0, 1, 2, 3)

    # now continue from 4th iteration until the condition is met again       
Run Code Online (Sandbox Code Playgroud)

同样,只要满足条件,就会发生这种情况。

Meh*_*hdi 5

跳过每次会议条件(后4个步骤(i % 300) == 0)等于跳过012,和3。您可以简单地更改条件以跳过所有这些步骤(i % 300) < 4

for i in range(0, 200000):
    # (when 0 % 300 it meets this criteria) 
    if (i % 300) < 4: # Skips iteration when remainder satisfier condition            
    #if (i % 300) in (0,1,2,3): # or alternative skip condition
        # whenever this condition is met skip 4 iterations forward
        # now skip 4 iterations --- > (0, 1, 2, 3)
        continue

    # now continue from 4th iteration 
    print(i)
Run Code Online (Sandbox Code Playgroud)

  • 它是“&lt; 4”,因为您想要跳过的 4 次该条件都为真。如果你想迭代一个集合,它可能会崩溃。(但它对此效果很好:) (2认同)