[BangPypers] A doubt in list comprehension
sridhar.ratna at gmail.com
Sat Sep 12 04:18:49 CEST 2009
On Fri, Sep 11, 2009 at 4:57 PM, Shashwat Anand
<anand.shashwat at gmail.com> wrote:
> However what if I want an if-else loop in nested for loop.
Are you referring to this:
['EVEN' if x%2==0 else 'ODD' for x in range(10)]
> for i in range(10):
> for j in range(10):
> for k in range(10):
> if i == j and j == k:
> print "All equal"
> elif (i == j and j != k) or (i == k and j != k):
> print "2 equal"
> print "None equal"
If you are asking how to achieve the above code using list
comprehensions, then try
return ["All equal" if i==j and j==k else (
"2 equal" if (i==j and j!=k) or (i==k and j!=k) \
else "None equal")
for i in range(10)
for j in range(10)
for k in range(10)]
For convenience, I pasted the code here: http://gist.github.com/185695
Speaking personally, your original code is just fine - it is simpler
than the list comprehension version above.
More information about the BangPypers