Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, next iteration of the loop over a loop

Tags:

python

I need to get the next item of the first loop given certain condition, but the condition is in the inner loop. Is there a shorter way to do it than this? (test code)

    ok = 0
    for x in range(0,10):
        if ok == 1:
            ok = 0
            continue
        for y in range(0,20): 
            if y == 5:
                ok = 1
                continue

What about in this situation?

for attribute in object1.__dict__:
    object2 = self.getobject()
    if object2 is not None:
        for attribute2 in object2: 
            if attribute1 == attribute2:
                # Do something
                #Need the next item of the outer loop

The second example shows better my current situation. I dont want to post the original code because it's in spanish. object1 and object2 are 2 very different objects, one is of object-relational mapping nature and the other is a webcontrol. But 2 of their attributes have the same values in certain situations, and I need to jump to the next item of the outer loop.

like image 695
Pablo Avatar asked Feb 09 '10 15:02

Pablo


People also ask

How do you go to the next iteration in a for loop in Python?

You can use the continue statement if you need to skip the current iteration of a for or while loop and move onto the next iteration.

How do you make a loop go to next iteration?

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement.

How do I skip the next iteration in Python?

Use the continue statement inside the loop to skip to the next iteration in Python. However, you can say it will skip the current iteration, not the next one.

How do you break out of a loop in Python?

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.


1 Answers

Replace the continue in the inner loop with a break. What you want to do is to actually break out of the inner loop, so a continue there does the opposite of what you want.

ok = 0
for x in range(0,10):
    print "x=",x
    if ok == 1:
        ok = 0
        continue
    for y in range(0,20): 
        print "y=",y
        if y == 5:
            ok = 1
            break
like image 122
MAK Avatar answered Sep 30 '22 09:09

MAK