[Tutor] Multiple for and if/else statements into a single list comprehension
Jignesh Sutar
jignesh.sutar at gmail.com
Mon Mar 17 11:19:40 CET 2014
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140317/d281d593/attachment.html>
More information about the Tutor
mailing list