Inline Conditionals?
Alex Martelli
aleaxit at yahoo.com
Thu Aug 26 16:18:00 EDT 2004
Antoon Pardon <apardon at forel.vub.ac.be> wrote:
...
> When using list comprehension not having a ternary operator can be
> a PITA. It is of course possible I miss something but how am I
> supposed to do the following:
>
> [ x.property ? foo(x) : bar(x) for x in Somelist ]
If you HAVE to use an LC by doctor's order, the above effect might be
obtained by coding something like:
[ (bar,foo)[bool(x.property)](x) for x in Somelist ]
If your physician should relent and let you code normal Python, though,
aux = []
for x in Somelist:
if x.property:
aux.append(foo(x))
else
aux.append(foo(x))
would be vastly more readable; "sparse is better than dense" and any LC
is far too dense to be Pythonic here.
Alex
More information about the Python-list
mailing list