深入分析python的and or 返回值

2019-10-30     科技i關注

在Python 中,and 和 or 執行布爾邏輯演算,如你所期待的一樣,但是它們並不返回布爾值;而是,返回它們實際進行比較的值之一。

一、and:

>>> 'a' and 'b'

'b'

>>> '' and 'b'

''

>>> 'a' and 'b' and 'c'

'c'

在布爾上下文中從左到右演算表達式的值,如果布爾上下文中的所有值都為真,那麼 and 返回最後一個值。

如果布爾上下文中的某個值為假,則 and 返回第一個假值

二、or:

>>> 'a' or 'b'

'a'

>>> '' or 'b'

'b'

>>> '' or [] or {}

{}

>>> 0 or 'a' or 'c'

'a'

使用 or 時,在布爾上下文中從左到右演算值,就像 and 一樣。如果有一個值為真,or 立刻返回該值

如果所有的值都為假,or 返回最後一個假值

注意 or 在布爾上下文中會一直進行表達式演算直到找到第一個真值,然後就會忽略剩餘的比較值

三、and-or:

and-or 結合了前面的兩種語法,推理即可。

>>> 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。

and-or 技巧,bool and a or b 表達式,當 a 在布爾上下文中的值為假時,不會像 C 語言表達式 bool ? a : b 那樣工作。

四、安全使用and-or

>>> a=""

>>> b="second"

>>> (1 and [a] or [b])

['']

>>> (1 and [a] or [b])[0]

''

>>>

由於 [a] 是一個非空列表,所以它決不會為假。即使 a 是 0 或者 '' 或者其它假值,列表 [a] 也為真,因為它有一個元素。

一個負責的程式設計師應該將 and-or 技巧封裝成一個函數:

def choose(bool,a,b):

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

print choose(1,'','second') #''

更多技巧請《轉發 + 關注》哦!

文章來源: https://twgreatdaily.com/zh-tw/KyDwGm4BMH2_cNUge0He.html