Does Python have a ternary conditional operator?

2018-12-30 22:26发布

If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?

25条回答
裙下三千臣
2楼-- · 2018-12-30 23:02

Absolutely, and it is incredibly easy to understand.

general syntax : first_expression if bool_expression_is_true else second_expression

Example: x= 3 if 3 > 2 else 4 
# assigns 3 to x if the boolean expression evaluates to true or 4 if it is false
查看更多
倾城一夜雪
3楼-- · 2018-12-30 23:02

Does Python have a ternary conditional operator?

Yes. From the grammar file:

test: or_test ['if' or_test 'else' test] | lambdef

The part of interest is:

or_test ['if' or_test 'else' test]

So, a ternary conditional operation is of the form:

expression1 if expression2 else expression3

expression3 will be lazily evaluated (that is, evaluated only if expression2 is false in a boolean context). And because of the recursive definition, you can chain them indefinitely (though it may considered bad style.)

expression1 if expression2 else expression3 if expression4 else expression5 # and so on

A note on usage:

Note that every if must be followed with an else. People learning list comprehensions and generator expressions may find this to be a difficult lesson to learn - the following will not work, as Python expects a third expression for an else:

[expression1 if expression2 for element in iterable]
#                          ^-- need an else here

which raises a SyntaxError: invalid syntax. So the above is either an incomplete piece of logic (perhaps the user expects a no-op in the false condition) or what may be intended is to use expression2 as a filter - notes that the following is legal Python:

[expression1 for element in iterable if expression2]

expression2 works as a filter for the list comprehension, and is not a ternary conditional operator.

Alternative syntax for a more narrow case:

You may find it somewhat painful to write the following:

expression1 if expression1 else expression2

expression1 will have to be evaluated twice with the above usage. It can limit redundancy if it is simply a local variable. However, a common and performant Pythonic idiom for this use-case is to use or's shortcutting behavior:

expression1 or expression2

which is equivalent in semantics. Note that some style-guides may limit this usage on the grounds of clarity - it does pack a lot of meaning into very little syntax.

查看更多
刘海飞了
4楼-- · 2018-12-30 23:04

Syntax: The Ternary operator will be given as:

[on_true] if [expression] else [on_false]

e.g

x, y = 25, 50
big = x if x < y else y
print(big)
查看更多
无与为乐者.
5楼-- · 2018-12-30 23:05

if variable is defined and you want to check if it has value you can just a or b

def test(myvar=None):
    # shorter than: print myvar if myvar else "no Input"
    print myvar or "no Input"

test()
test([])
test(False)
test('hello')
test(['Hello'])
test(True)

will output

no Input
no Input
no Input
hello
['Hello']
True
查看更多
无与为乐者.
6楼-- · 2018-12-30 23:07

More a tip than an answer (don't need to repeat the obvious for the hundreth time), but I sometimes use it as a oneliner shortcut in such constructs:

if conditionX:
    print('yes')
else:
    print('nah')

, becomes:

print('yes') if conditionX else print('nah')

Some (many :) may frown upon it as unpythonic (even, ruby-ish :), but I personally find it more natural - i.e. how you'd express it normally, plus a bit more visually appealing in large blocks of code.

查看更多
不流泪的眼
7楼-- · 2018-12-30 23:08
a if condition else b

Just memorize this pyramid if you have trouble remembering:

     condition
  if           else
a                   b 
查看更多
登录 后发表回答