如何基于if条件跳过for循环中的一些迭代?

时间:2019-08-18 16:26:47

标签: 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       

类似地,只要满足条件,就应该发生这种情况。

2 个答案:

答案 0 :(得分:3)

在每个满足条件((i % 300) == 0)之后跳4个步骤等于跳过0123。您只需更改条件即可使用(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)

答案 1 :(得分:1)

您可以将迭代器(range)保存在变量中,并在需要时在其上调用next(it)。请注意,这将丢弃这些值。

# Note that we call iter to get an iterator. `range` is an iterable
# that returns another iterator so that it can be used multiple
# times in a for loop.
it = iter(range(200000))

for i in it:
    if not i%300:
        for _ in range(4): # 4 is the amount of values to skip
            i = next(it)   # Update `i` for use later on

    # `i` will never be a multiple of 300; it is updated above
    ...