菜鸟学院
Python 三元表达式
时间 2020-05-09
标签
python
三元
3元
表达式
Python 2.5中,定义了三元表达式,简化了条件表达式:
语法格式:
X if C else Y
有了三元表达式,你只需一行就能完成条件判断和赋值操做:
x, y = 3, 4
if x<y :
smaller= x
else
smaller =y
在之前 Python程序员大多这样作
smaller= (x<y and [x] or [y])[0]
smaller
3
如今 只需一句
smaller = x if x<y else y
smaller
3