三目运算也叫三元运算,在许多编程语言中都有这种简便运算。相对于 Java 、C# 、JavaScript 等编程语言中的
condition ? true_part : false_part
语法,Python 稍有不同。
condition and true_part or false_part
如果 condition
运行结果为 True 的话,返回 true_part
,否则返回 false_part
如:
1
2
3
4
5
>>> a=10
>>> a==10 and 'a is 10' or 'a is not 10'
'a is 10'
>>> a==20 and 'a is 20' or 'a is not 20'
'a is not 20'
但是如果 condition
为 True,且 true_part
为 False 的时候,结果就有些不同了
1
2
3
>>> a=10
>>> a==10 and '' or 'a is not 10'
'a is not 10'
在这种情况下,返回结果就是 false_part
。因此它在条件判断的时候有两级条件判断,首先是 condition
,其次是 true_part
, 这种用法用的时候需要注意。
true_part if condition else false_part
如果 condition
运行结果为 True 的话,返回 true_part
,否则返回 false_part
如:
1
2
3
>>> a=10
>>> 'a is 10' if a==10 else 'a is not 10'
'a is 10'
condition1 and condition2 和 condition1 or condition2
Python 中的 and
和 or
除了可以作为逻辑运算符外,还可以用于短路运算。
condition1 and condition2
如果condition1
和condition2
都判断为 True 的话,则返回condition2
,否则只要有一个判断为 False 的话,则返回第一个假值。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
>>> a=['a'] >>> b=['b'] >>> a and b ['b'] >>> a=[] >>> b=['b'] >>> a and b [] >>> a=['a'] >>> b=[] >>> a and b [] >>> a='' >>> b=[] >>> a and b ''
condition1 or condition2
如果condition1
判断为 True 的话,返回condition1
,否则返回condition2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
>>> a=['a'] >>> b=['b'] >>> a or b ['a'] >>> a=['a'] >>> b=[] >>> a or b ['a'] >>> a=[] >>> b=['b'] >>> a or b ['b'] >>> a='' >>> b=[] >>> a or b []