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 02:52
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
查看更多
仙女界的扛把子
3楼-- · 2020-05-23 02:54
for a in aa:
     for b in bb:
         for c in cc:
            if c == a[b]:
                break
         else:
             continue
         break

Python supports for...else statements. else block is evaluated if the inner break is not fired.

查看更多
Lonely孤独者°
4楼-- · 2020-05-23 02:57

Exception handling beats setting variables all over the place 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
查看更多
狗以群分
5楼-- · 2020-05-23 02:59

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 continue if no break was used. The else will 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.

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

    break
查看更多
地球回转人心会变
6楼-- · 2020-05-23 03:08

If you have too many embedded loops, it might be time for a refactor. In this case, I believe the best refactor is to move your loops into a function and use a return statement. That will force-exit out of any number of loops. For example:

def example(self, drug_input):
    ok = False
    for x in drug_input["names"]:
        for y in range(drug_input["number_of_drugs"]):
            for z in drug_input["list_of_drugs"]:
                # do stuff
                if ok:
                    return drug_costs

Now, perhaps reformulating your logic like this is tricky, but I bet the refactoring will help in other ways.

查看更多
Melony?
7楼-- · 2020-05-23 03:09

Latest PEP I see requesting this feature is 3136 (and was rejected): 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):

class LocalBreak(Exception): pass

try:
   for i in ...:
       for h in ...:
           for j in ...:
              if should_break(j):
                 raise LocalBreak()
except LocalBreak:
   pass
查看更多
登录 后发表回答