On 03/17/2014 11:22 AM, Jignesh Sutar wrote:
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()
You can do it by reformulating your inner block into an expression (here, using
a ternary if expression), which will then become the expression part of the
comprehension. However, a few remarks:
* don't do that: the only advantage is to make your code unreadable
* you may reformulate using 2 comprehensions; if you don't want intermediate
lists, use a generator expression for the inner one
* above, the inner j is a new variable with a distinct meaning: why do you call
it j?
* do you really need string concat to perform arithmetic?
d
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor