Python 如何跳过for循环中的特定迭代?
基本上,我有一个嵌套的for循环。在内部循环中,发生了一些事情,我可以跳过3、4、5或需要跳过的迭代次数。但是我不能对外环做同样的事情。 希望这是有道理的。 这是我的密码:Python 如何跳过for循环中的特定迭代?,python,list,loops,iteration,Python,List,Loops,Iteration,基本上,我有一个嵌套的for循环。在内部循环中,发生了一些事情,我可以跳过3、4、5或需要跳过的迭代次数。但是我不能对外环做同样的事情。 希望这是有道理的。 这是我的密码: phraseArray = [] phraseArray2 = [] counterAdd = 0 counter = 0 try: for i in range(len(wordArray)): for j in range(len(wordArray2)): if wor
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用于跳过某些迭代。我不能对外循环做同样的事情,因为内循环改变了计数器变量,它决定了需要跳过多少次迭代。有什么建议吗
提前谢谢大家!:) 跳过循环多次迭代的一般形式可以这样工作
skips = 0
for x in y:
if skips:
skips -= 1
continue
#do your stuff
#maybe set skips = something
您不能在外部循环中使用“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
和/或break
语句。为外循环维护另一个计数器
,并使用i+=counter
跳过?您应该将代码简化到再现问题所需的最低限度,并更明确地说明要跳过迭代的条件。也就是说,您可能对添加到j
或i
中的。这与C或java中的for
循环不同。您想用代码解决什么问题?我觉得有一个更简单的解决方案。函数“skip”中的islice方法是什么?@ProSagramor--对不起,应该是,而不仅仅是islice
。(我从itertools消费配方中抄得太近了)