python: exit out of two loops

2020-05-23 02:45发布

  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: ?

标签: python
11条回答
孤傲高冷的网名
2楼-- · 2020-05-23 03:10

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 all and any to avoid writing explicit loops.

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

查看更多
Ridiculous、
3楼-- · 2020-05-23 03:13

I would consider putting the two inner loops in function and using return from 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.

查看更多
成全新的幸福
4楼-- · 2020-05-23 03:14
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.

查看更多
乱世女痞
5楼-- · 2020-05-23 03:14

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 
查看更多
Luminary・发光体
6楼-- · 2020-05-23 03:15

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

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

now, a break from the for brand nested loop will go back to the for row outer loop level. Of course, this works only when the code that is here replaced by ... does not need to see the drug name bound to the drug currently being examined. Is that the case for you?

查看更多
登录 后发表回答