[Tutor] Multiple for and if/else statements into a single list comprehension
Peter Otten
__peter__ at web.de
Mon Mar 17 12:18:52 CET 2014
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()
> Many thanks in advance.
Need I say that it is a bad idea to build overly complex list
comprehensions? Under that proviso:
The first step is always to ensure that there is a single expression in the
inner loop. I'm keeping as similar as possible to your loops:
for i in xrange(1, 20):
for j in xrange(1, 10):
print "%02d_%02d" % (i,
int(("8" if j < 6 else "9") + str(j)))
Now the translation is mechanical
for x in a:
for y in b:
expr
becomes
[expr for x in a for y in b]
or (using a genexp rather than a listcomp as you are going to print it
anyway)
print "\n".join(
"%02d_%02d" % (i, int(("8" if j < 6 else "9") + str(j)))
for i in xrange(1, 20)
for j in xrange(1, 10))
But again: don't do that ;)
By the way, using locals() is another bad idea, plus it does not capture the
loop vars of genexps (all pythons) and listcomps (python3).
PS: a simple alternative:
print "\n".join(
"%02d_%02d" % (i, k)
for i in range(1, 20)
for k in range(81, 86) + range(96, 100))
More information about the Tutor
mailing list