If/then style question

Ian Kelly ian.g.kelly at gmail.com
Thu Dec 16 18:02:38 EST 2010


On Thu, Dec 16, 2010 at 3:41 PM, Stefan Sonnenberg-Carstens
<stefan.sonnenberg at pythonmeister.com> wrote:
> return [x for x,y in
> ((bad1,some_bad_condition),(bad2,some_other_bad_condition),(bad3,yet_another_bad_condition),(good1,do_some_useful_stuff()
> or True)) if x][0]

This doesn't work.  do_some_usefull_stuff() gets called during the
tuple construction regardless of the conditions, not during the list
comprehension execution as you would want.

Here's my take on an unreadable one-liner:

return reduce(lambda x, y: (x or (y[0]() and y[1])),
[(some_bad_condition, bad1), (some_other_bad_condition, bad2),
(yet_another_bad_condition, bad3), (lambda: (do_some_useful_stuff() or
True), good1)], None)

This of course assumes that bad1, bad2, and bad3 all evaluate as true.

Cheers,
Ian



More information about the Python-list mailing list