Pablo Pablo - 3 months ago 11
Python Question

Python, next iteration of the loop over a loop

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.

MAK MAK
Answer

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
Comments