python:退出两个循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3357255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:38:03  来源:igfitidea点击:

python: exit out of two loops

python

提问by l--''''''---------''''''''''''

  for row in b:
    for drug in drug_input:
      for brand in brand_names[drug]:

from the third loop how do i exit the current loop and go to the next value of for row in b:?

从第三个循环我如何退出当前循环并转到下一个值for row in b:

采纳答案by Donald Miner

This one uses a boolean to see if you are done yet:

这个使用布尔值来查看您是否已完成:

done = False
for x in xs:
    for y in ys:
        if bad:
            done = True
            break

    if done:
        break

This one will continueif no break was used. The elsewill be skipped over if there was a break, so it will see the next break. This approach has the benefit of not having to use a variable, but may be harder to read to some.

continue如果没有使用中断,这将是。在else将被跳过,如果有一个突破,所以它会看到未来break。这种方法的好处是不必使用变量,但对某些人来说可能更难阅读。

for x in xs:
    for y in ys:
        if bad:
            break
    else:
        continue

    break

回答by Caleb Hattingh

Untested:

未经测试:

inner_termination=False
for row in b:
    for drug in drug_input:
       for brand in brand_names[drug]:
           <blah>
           if break_condition:
               inner_termination=True
               break 
           <blah>
       if inner_termination:
           inner_termination=False
           break 

回答by Ned Batchelder

for row in b:
   more_drugs = True
   for drug in drug_input:
      for brand in brand_names[drug]:
          if something:
              more_drugs = False
              break

      if not more_drugs:
          break

Python doesn't have a control structure for breaking from two loops at once, so you need to do something manual like this.

Python 没有用于同时中断两个循环的控制结构,因此您需要像这样手动执行一些操作。

回答by Mark Byers

If you have three levels of looping in one method then you probably need to rethink your design.

如果您在一种方法中有三级循环,那么您可能需要重新考虑您的设计。

  • Split your method up into smaller, simpler methods.
  • Use a list comprehension and methods like alland anyto avoid writing explicit loops.
  • 将您的方法拆分为更小、更简单的方法。
  • 使用列表理解和方法,如allany避免编写显式循环。

Doing either of these should mean that you no longer have this issue.

执行其中任何一项应该意味着您不再有此问题。

回答by Teodor Pripoae

for row in b:
    ok = True
    for drug in drug_input:
        if not ok:
            break;
        for brand in brand_names[drug]:
            if not ok:
                break
            if whatever:
                ok = False

回答by Alex Martelli

try/except/raise, as suggested in @gddc's comment, is one possibility. Another one is to "wrap up" the two nested loops into one:

try/ except/ raise,如@ GDDC的评论所说,是一种可能性。另一种是将两个嵌套循环“包装”为一个:

for row in b:
  for brand in (b for d in drug_input for b in brand_names[d]):
    ...

now, a breakfrom the for brandnested loop will go back to the for rowouter loop level. Of course, this works only when the code that is here replaced by ...does not need to see the drugname bound to the drug currently being examined. Is that the case for you?

现在,break来自for brand嵌套循环的 a 将返回到for row外循环级别。当然,这只有在这里替换的代码...不需要看到drug绑定到当前正在检查的药物的名称时才有效。你是这种情况吗?

回答by Tony Veijalainen

I would consider putting the two inner loops in functionand using returnfrom there. Probably rethinking what you are doing and how gives the better alternative to that though.

我会考虑将两个内部循环放在函数中并从那里使用返回。可能会重新考虑您在做什么以及如何提供更好的替代方案。

Could you give your current pseudo code, input and output, so we could try to remove the need for the break in first place? We need to see where the loop variables are used or better still, what is the goal of the processing.

您能否提供当前的伪代码、输入和输出,以便我们首先尝试消除对中断的需要?我们需要查看循环变量的使用位置,或者更好的是,处理的目标是什么。

回答by brianz

Exception handling beats setting variables all over the place IMO

异常处理胜过在 IMO 各地设置变量

for row in b:
    for drug in drug_input:
        try:
            for brand in brand_names[drug]:
                if some_condition:
                    raise StopIteration
        except StopIteration:
            break

回答by Nathan Ernst

Latest PEP I see requesting this feature is 3136 (and was rejected): http://mail.python.org/pipermail/python-3000/2007-July/008663.html

我看到请求此功能的最新 PEP 是 3136(并被拒绝):http: //mail.python.org/pipermail/python-3000/2007-July/008663.html

Closest & cleanest thing I could see to what you want to do would be do the following (and since even type names are scoped, you could declare LocalBreak within the function its needed):

我可以看到你想要做的最接近和最干净的事情是执行以下操作(并且由于即使类型名称也有范围,你可以在它需要的函数中声明 LocalBreak ):

class LocalBreak(Exception): pass

try:
   for i in ...:
       for h in ...:
           for j in ...:
              if should_break(j):
                 raise LocalBreak()
except LocalBreak:
   pass

回答by Elmo Van Kielmo

for a in aa:
     for b in bb:
         for c in cc:
            if c == a[b]:
                break
         else:
             continue
         break

Python supports for...elsestatements. elseblock is evaluated if the inner breakis not fired.

Python 支持for...else语句。else如果内部break未触发,则评估块。