[Tutor] Multiple for and if/else statements into a single list comprehension

Jignesh Sutar jsutar at gmail.com
Mon Mar 17 23:35:48 CET 2014


Thanks Peter/Denis. I wasn't aware of genexp. I see how you have adapted
the code to make it work, I'll adapt the same in my program. Good point
about duplicating j , Denis, I guess I was happy to override the outer j as
it was intermediate.


On 17 March 2014 12:36, spir <denis.spir at gmail.com> wrote:

> 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 at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140317/bd0429ba/attachment-0001.html>


More information about the Tutor mailing list