如何跳过for循环中的特定迭代?

2024-09-26 04:57:17 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我有一个嵌套的for循环。在内部循环中,发生了一些事情,我可以跳过3、4、5次或者需要跳过多少次迭代。但我不能对外环做同样的事。 希望这是有道理的。 这是我的代码:

phraseArray = []
phraseArray2 = []
counterAdd = 0
counter = 0

try:
    for i in range(len(wordArray)):
        for j in range(len(wordArray2)):
            if wordArray[i]==wordArray2[j]:
                counter = 0
                counter2=3
                while True:
                    if wordArray[i+counter]==wordArray2[j+counter]:
                        counter = counter+1
                        if counter==3:                                           
                            phraseArray.append(wordArray[i+0])
                            phraseArray.append(wordArray[i+1])
                            phraseArray.append(wordArray[i+2])
                        elif counter>3:
                            phraseArray.append(wordArray[i+counter2])
                            counter2 = counter2+1
                    else:
                         phraseArray.append(" ")
                         j=j+counter
                         break

except IndexError:
    print phraseArray2

j=j+1用于跳过某些迭代。我不能对外部循环做同样的操作,因为内部循环更改了计数器变量,该变量指示需要跳过多少次迭代。有什么建议吗?在

提前谢谢各位!:)


Tags: 代码inforlenifcounterrange事情
3条回答

不能在外循环中使用“break”,因为这将完成循环而不是跳过它,您可以使用一些IF语句来控制所需的情况。有点像

if(condition=skip):
   #do nothing
else:
  # do

我会在这里使用迭代器。在

import itertools

def skip(iterable, n):
    next(itertools.islice(iterable, n, n), None)

outer_numbers = iter(range(...))
for i in outer_numbers:
    inner_numbers = iter(range(...))
    for j in inner_numbers:
        if condition:
            skip(outer_numbers, 3)  # skip 3 items from the outer loop.
            skip(inner_numbers, 2)  # skip 2 items from the inner loop.

当然,您可能想要/需要continue和/或{}语句。在

跳过循环多次迭代的一般形式可以这样工作。在

skips = 0
for x in y:
    if skips:
        skips -= 1
        continue

    #do your stuff

    #maybe set skips = something

相关问题 更多 >