Python 當中的and和or

1、and程序員

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

舉例:ide

1函數

2it

3table

4class

5技巧

6語法

>>>   'a'       and   'b'程序

'b'

>>>   ''       and   'b'

''

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

'c'

在布爾上下文中從左到右演算表達式的值,若是布爾上下文中的全部值都爲真,那麼 and 返回最後一個值。

若是布爾上下文中的某個值爲假,則 and 返回第一個假值

2、or:

1

2

3

4

5

6

7

8

>>>   'a'       or   'b'

'a'

>>>   ''       or   'b'

'b'

>>>   ''       or [] or {}

{}

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

'a'

使用 or 時,在布爾上下文中從左到右演算值,就像 and 同樣。若是有一個值爲真,or 馬上返回該值

若是全部的值都爲假,or 返回最後一個假值

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

3、and-or:

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

1

2

3

4

5

6

7

8

9

10

11

>>> 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 那樣工做。

4、安全使用and-or

1

2

3

4

5

6

>>> a=  ""

>>> b=  "second"

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

[  ''  ]

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

''

>>>

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

一個負責的程序員應該將 and-or 技巧封裝成一個函數:

1

2

3

def choose(bool,a,b):

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

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

相關文章
相關標籤/搜索