Is it possible to get two nested for statements followed by a nested
if/else statement all into a single list comprehension ie. the equivalent
of the below:


for i in xrange(1,20):
    for j in xrange(1,10):
        if j<6:
            j=int("8"+str(j))
        else:
            j=int("9"+str(j))
        print "%(i)02d_%(j)02d" % locals()


# double for statement without if/else works
print "\n".join(["%(i)02d_%(j)02d" % locals() for i in xrange(1,20) for j
in xrange(1,10)])

#now try to incorporate if/else part
#failed attempt 1
print "\n".join(["%(i)02d_%(j)02d" % locals() for i in xrange(1,20) for j
in xrange(1,10) j=int("8"+str(j)) if j<6 else int("9"+str(j))])

#failed attempt 2
print "\n".join(["%(i)02d_%(j)02d" % locals() for i in xrange(1,20)
j=int("8"+str(j)) if j<6 else int("9"+str(j)) for j in xrange(1,10)])

#failed attempt 3
print "\n".join(["%(i)02d_%(j)02d" % locals() j=int("8"+str(j)) if j<6 else
int("9"+str(j)) for i in xrange(1,20)  for j in xrange(1,10)])


Many thanks in advance.
Jignesh
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to