python的and-or语法可以实现效果类似C语言3目运算bool?a:b语法,格式为:(bool and [a] or [b])[0]。
通常可以简单封装为一个函数使用:
def select(bool, a, b):
return (bool and [a] or [b])[0]
select(1, "first", "second") ===> first
select(0, "first", "second") ===>second
在python中and和or执行布尔演算并不是返回True或者False,而是按照自左向右顺序进行运算,返回比较后的值。
如:
print ( 'a' and 'b') => 'b'
print('a' or 'b') => 'a'
print ('a' and 0 and False) =>0
print ('a' and False and 0) =>False
print ('0' or False) =>False
以上还有一个规律:
‘and’运算返回最后一个真,返回第一个假;‘or‘运算返回第一个真,返回最后一个假