Is there something similar to ?: operator (C/C++) in Python?

Ron Adam rrr at ronadam.com
Thu Jun 30 14:19:26 EDT 2005


Antoon Pardon wrote:
> Op 2005-06-29, Scott David Daniels schreef <Scott.Daniels at Acm.Org>:
> 
>>Roy Smith wrote:
>>
>>>Andrew Durdin <adurdin at gmail.com> wrote:
>>>
>>>>Corrected version:
>>>>   result = [(lambda: expr0), lambda: expr1][bool(cond)]()
>>
>>Sorry, I thought cond was a standard boolean.
>>Better is:
>>     result = [(lambda: true_expr), lambda: false_expr][not cond]()
> 
> 
> How about the following:
> 
>   result = (cond and (lambda: true_expr) or (lambda: false_expr))()
> 

That works as long as long as they are expressions, but the ? format 
does seem to be more concise I admit.


To use *any* expressions in a similar way we need to use eval which is a 
lot slower unfortunately.

    result = eval(['expr0','expr1'][cond])


A thought occurs to me that putting index's before the list might be an 
interesting option for expressions.

    result = expr[expr0,expr1]


This would probably conflict with way too many other things though. 
Maybe this would be better?

    result = index from [expr0,expr1]


Where index can be an expression.  That is sort of an inline case 
statement.  Using a dictionary it could be:

    result = condition from {True:expr1, False:expr0}


As a case using values as an index:

     case expr from [
        expr0,
        expr2,
        expr3 ]


Or using strings with a dictionary...

     case expr from {
        'a':expr0,
        'b':expr1,
        'c':expr3 }
     else:
        expr4

Reads nice, but can't put expressions in a dictionary or list without 
them being evaluated first, and the [] and {} look like block brackets 
which might raise a few complaints.

Can't help thinking of what if's.  ;-)

Cheer's
Ron



More information about the Python-list mailing list