Refactor several nested for loops with conditions

Viewed 325

Consider following piece of code

for a in generator1():
    if test(a):
        for b in generator2():
            if test(a, b):
                for c in generator3():
                    if test(a, b, c):
                        print "Found {} {} {}".format(a, b, c)

Using test before each loop is essential since generators can yield a lot of values (10^6-10^8). I do not want to do expensive computations when it is clear that due to value of a or b entire triple won't pass test.

Can this code be simplified? What if I want to add more inner loops (test fours of fives)?

1 Answers
Related