如果 Python 没有三元条件运算符,是否可以使用其他语言构造来模拟一个?
Ternary Operator in different programming Languages
Here I just try to show some important difference in ternary operator
between a couple of programming languages.
Ternary Operator in Javascript
var a = true ? 1 : 0;
# 1
var b = false ? 1 : 0;
# 0
Ternary Operator in Ruby
a = true ? 1 : 0
# 1
b = false ? 1 : 0
# 0
Ternary operator in Scala
val a = true ? 1 | 0
# 1
val b = false ? 1 | 0
# 0
Ternary operator in R programming
a <- if (TRUE) 1 else 0
# 1
b <- if (FALSE) 1 else 0
# 0
Ternary operator in Python
a = 1 if True else 0
# 1
b = 1 if False else 0
# 0
</div>
You might often find
cond and on_true or on_false
but this lead to problem when on_true == 0
>>> x = 0
>>> print x == 0 and 0 or 1
1
>>> x = 1
>>> print x == 0 and 0 or 1
1
where you would expect for a normal ternary operator this result
>>> x = 0
>>> print 0 if x == 0 else 1
0
>>> x = 1
>>> print 0 if x == 0 else 1
1
</div>
One of the alternatives to Python's conditional expression
"yes" if boolean else "no"
is the following:
{True:"yes", False:"no"}[boolean]
which has the following nice extension:
{True:"yes", False:"no", None:"maybe"}[boolean_or_none]
The shortest alternative remains:
("no", "yes")[boolean]
but there is no alternative to
yes() if boolean else no()
if you want to avoid the evaluation of yes()
and no()
, because in
(no(), yes())[boolean] # bad
both no()
and yes()
are evaluated.
a if condition else b
Just memorize this pyramid if you have trouble remembering:
condition
if else
a b
</div>
Ternary conditional operator simply allows testing a condition in a single line replacing the multiline if-else making the code compact.
Syntax :
[on_true] if [expression] else [on_false]
1- Simple Method to use ternary operator:
# Program to demonstrate conditional operator
a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min) # Output: 10
2- Direct Method of using tuples, Dictionary, and lambda:
# Python program to demonstrate ternary operator
a, b = 10, 20
# Use tuple for selecting an item
print( (b, a) [a < b] )
# Use Dictionary for selecting an item
print({True: a, False: b} [a < b])
# lamda is more efficient than above two methods
# because in lambda we are assure that
# only one expression will be evaluated unlike in
# tuple and Dictionary
print((lambda: b, lambda: a)[a < b]()) # in output you should see three 10
3- Ternary operator can be written as nested if-else:
# Python program to demonstrate nested ternary operator
a, b = 10, 20
print ("Both a and b are equal" if a == b else "a is greater than b"
if a > b else "b is greater than a")
Above approach can be written as:
# Python program to demonstrate nested ternary operator
a, b = 10, 20
if a != b:
if a > b:
print("a is greater than b")
else:
print("b is greater than a")
else:
print("Both a and b are equal")
# Output: b is greater than a
</div>
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.