三目运算符,是c语言的重要组成部分。条件运算符是唯一有三个操作数的运算符,又称为三元运算符。
在c语言风格的语言中,三元操作符的形式如下:
<span style="font-family:Arial;font-size:12px;color:#333333;"><condition> ? <expression1> : <expression2></span>
但是在python中并没有这样的操作符,在python 2.5之前,可以用如下的方式表示三元运算符
<span style="font-family:Arial;font-size:12px;color:#333333;">(X, Y)[C]</span>
其中C为条件,如果C不成立,那么元祖中的第一个元素X被返回,如果C成立,那么返回第二个元素Y。
P.S. 不推荐。 因为表达式X,Y都会执行,而我们仅需要一个。
<span style="font-family:Arial;color:#333333;"><span style="font-size:12px;">val = float(raw_input('Age: '))
print 'You should be', ('working','retired')[val>65]
# result
Age: 67
You should be retired</span></span>
表达式变形:
age = 15
# Selecting an item from a tuple
print(('adult', 'kid')[age < 20])
# Which is the equivalent of...
print(('adult', 'kid')[True])
# Or more explicit by using dict
print({True: 'kid', False: 'adult'}[age < 20])
# using lambda
age = 15
print((lambda: 'kid', lambda: 'adult')[age > 20]())
# using and/or
age = 15
print (age < 20) and 'kid' or 'adult'
从python 2.5开始,当PEP 308被采用之后,引入了单行的if表达式,用来替代三目运算符。
<expression1> if <condition> else <expression2>
这种方式中,只有当条件成立的时候,表达式1才被执行并返回,不成立的时候,表达式2成立并返回。这样,表达式只有一个被执行,不会浪费资源。
val=float(raw_input('Age:'))
print 'You should be','retired' if val>65 else 'working'
# result
Age:76
You should be retired
使用如下代码检测:
def f1():
print "f1!"
return 1
def f2():
print "f2!"
return 2
if __name__ == "__main__":
v = f1() if True else f2()
print "v =", v
print "-" * 10
v2 = f1() if False else f2()
print "v2 =", v2
# result
f1!
v = 1
----------
f2!
v2 = 2
我们可以看到,最开始只执行f1方法,而第二个表达式只执行了f2方法,并不会两个方法都执行。
三元表达式的变形
age = 15
print('kid') if age < 12 else ('teenager') if age < 18 else ('adult')
# teenager
# Which is the same as:
if age < 18:
if age < 12:
print('kid')
else:
print('teenager')
else:
print('adult')
# teenager
我们可以用pprint来检查,python的三元表达式是从左往右的。
from pprint import pprint
pprint('expression_1') if pprint('condition_1') else pprint('expression_2') if pprint('condition_2') else pprint('expression_3')
# result
'condition_1'
'condition_2'
'expression_3'
参考:
http://www.pythoncentral.io/one-line-if-statement-in-python-ternary-conditional-operator/
http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator
http://oldj.net/article/python-ternary-operator/