Tuesday 9 February 2010

Python list comprehension with logic

test= [i if i in [1,2] else 0 for i in xrange(5)]

test= [i if i in [1,2] else 2*i if i in [3,4] else 0 for i in xrange(5)]

ie, the trailing `else' is essential.

No comments:

Post a Comment