Skip to content

python_andor

遇见王斌 edited this page Dec 7, 2018 · 2 revisions

and & or

对 python 而言

  • 其一,在不加括号时候,and 优先级大于 or
  • 其二,x or y 的值只可能是 x 或 y. x 为真就是 x, x 为假就是 y
  • 第三,x and y 的值只可能是 x 或 y. x 为真就是 y, x 为假就是 x

经典用法: bool and x or y

>>> a='first'
>>> b='second'
>>> 1 and a or b
'first'
>>> (1 and a) or b
'first'
>>> 0 and a or b
'second'
>>> (0 and a) or b
'second'
>>>

这个语法看起来类似于 C 语言中的 bool ? a : b 表达式。整个表达式从左到右进行演算,所以先进行 and 表达式的演算。 1 and 'first' 演算值为 'first',然后 'first' or 'second' 的演算值为 'first'。 0 and 'first' 演算值为 False,然后 0 or 'second' 演算值为 'second'。 and-or 主要是用来模仿 三目运算符 bool?a:b 的,即当表达式 bool 为真,则取 a 否则取 b。

优化版

上面程序在 a 为 0,’’,false,None 时,最终结果会输出 b 的值,改为如下方式即可:

(bool and [a] or [b])[0]

当把 a 变成列表形式 [a],可以排除这种例外,因为列表有元素 a,并不是空列表

Clone this wiki locally