搜尋
首頁後端開發Python教學分享python中and / or 的運算邏輯實例教學

python中and 和or 運算的核心思想——— 短路邏輯

  最近開始看廖雪峰的python教程,打算先把《learn python the hard way》放一放,因為最後幾章感覺還是有點難度(好吧,是我太弱了,不過慢慢來吧,一步一個腳印),想著看完廖雪峰的教程之後再回過頭來,或許能有些思路。

  好吧,言歸正傳,今天之所以寫這個,就是因為在廖雪峰教程裡filter 一章裡出現了and / or 的運算,之前的教程沒有提到過這個,剛看的時候有些困惑,一頭霧水,程式碼如下:

    #把一个序列中的空字符串删掉

    1>  def not_empty(s):
    2>      return s and s.strip()
    3>
    4>  filter(not_empty, ['A', '', 'B', None, 'C', '  '])

 

  後來在網路上查了一些關於and / or 的運算邏輯,加上自己的理解,總結如下(不知是否有誤,若有紕漏,還請各位斧正):

1. 包含一個邏輯運算子

  先從基本的概念著手,python中哪些物件會被當成False 呢?而哪些又是 True 呢?

**在Python中,None、任何數值類型中的0、空字串「」、空元組()、空列表[]、空字典{}都被當作False,還有自訂類型,如果實作了nonzero () 或 len () 方法且方法傳回0 或False,則其實例也被當作False,其他物件均為True。 **

  以下是最簡單的邏輯運算:

    True  and True    ==> True                  True  or True    ==> True
    True  and False   ==> False                 True  or False   ==> True
    False and True    ==> False                 False or True    ==> True
    False and False   ==> False                 False or False   ==> False

  利用上面兩點我們就可以舉一些例子:

example 1

    >>> a = [0, 1, '' ,3]
    >>> a[0] and a[1]
    0

  a [0] = 0 , a[1] = 1 , 所以a[0] and a[1] 就變成了0 and 1 (False and True),所以為0 (False)。

example 2

    >>> a = [0, 1, '' ,3]
    >>> a[2] and a[1]
    ''

  兩個同時為 False ,傳回左邊的值。

2. 包含兩個以上的邏輯運算子

  邏輯運算子 and / or 一旦不只一個,其運算規則的核心思想就是短路邏輯。好的,那我們就來了解短路思想(本人歸納,可能與網上其他人的有些出入,並且聽我慢慢分析):

表達式從左至右運算,若or 的左側邏輯值為True ,則短路or 後所有的表達式,直接輸出or 左側表達式。

表達式從左到右運算,若and 的左側邏輯值為False ,則短路其後所有and 表達式,直到有or 出現,輸出and 左側表達式到or 的左側,參與接下來的邏輯運算。

若 or 的左側為 False ,或 and 的左側為 True 則不能使用短路邏輯。

  可能有點抽象,沒關係,我們接下來就舉一些例子。

  這裡有一個巧妙的方法,能讓我們直觀地了解python 處理這些邏輯語句時的短路情況(我也是跟別人學的)

  好了,就讓我們從簡單的開始,假設全是and 語句或全是or 語句:

example 1

    1>  def a():
    2>      print 'A'
    3>      return []
    4>  def b():
    5>      print 'B'
    6>      return []
    7>  def c():
    8>      print 'C'
    9>      return 1
    10> def d():
    11>     print 'D'
    12>     return []
    13> def e():
    14>     print 'E'
    15>     return 1
    16>
    17> if a() and b() and c() and d() and e():
    18>     print 'ok'
    
    #显示结果如下
    A

  a() 的邏輯值為False ,其後均為and 語句,全部短路,最終返回a() 的表達式。

example 2

    1>  def a():
    2>      print 'A'
    3>      return 1
    4>  def b():
    5>      print 'B'
    6>      return 1
    7>  def c():
    8>      print 'C'
    9>      return []
    10> def d():
    11>     print 'D'
    12>     return []
    13> def e():
    14>     print 'E'
    15>     return 1
    16>
    17> if a() and b() and c() and d() and e():
    18>     print 'ok'

    #显示结果如下
    A
    B
    C

  a() 的邏輯值為True,不能短路其後,與b() 進行邏輯運算,傳回b() 的邏輯值True,與c()進行邏輯運算,傳回c() 的邏輯值False,其後均為and 語句, 則全部短路,最終傳回c() 的表達式。

example 3

    1>  def a():
    2>      print 'A'
    3>      return 1
    4>  def b():
    5>      print 'B'
    6>      return []
    7>  def c():
    8>      print 'C'
    9>      return 1
    10> def d():
    11>     print 'D'
    12>     return []
    13> def e():
    14>     print 'E'
    15>     return 1
    16>
    17> if a() or b() or c() or d() or e():
    18>     print 'ok'

    #显示结果如下
    A
    ok

  a() 的邏輯值為 True ,其後皆為 or 語句,全部短路,最終傳回 a() 的表達式。

example 4

    1>  def a():
    2>      print 'A'
    3>      return []
    4>  def b():
    5>      print 'B'
    6>      return []
    7>  def c():
    8>      print 'C'
    9>      return 1
    10> def d():
    11>     print 'D'
    12>     return []
    13> def e():
    14>     print 'E'
    15>     return 1
    16>
    17> if a() or b() or c() or d() or e():
    18>     print 'ok'

    #显示结果如下
    A
    B
    C
    ok

  a() 的邏輯值為True,不能短路其後,與b() 進行邏輯運算,傳回b() 的邏輯值False,與c()進行邏輯運算,傳回c() 的邏輯值True,其後均為or 語句,則全部短路,最終傳回c() 的表達式。

  下面我們就來講一下and 與or 語句同時存在的情況:

example 5

    1>  def a():
    2>      print 'A'
    3>      return []
    4>  def b():
    5>      print 'B'
    6>      return []
    7>  def c():
    8>      print 'C'
    9>      return 1
    10> def d():
    11>     print 'D'
    12>     return []
    13> def e():
    14>     print 'E'
    15>     return 1
    16> def f():
    17>     print 'F'
    18>     return 1
    19> def g():
    20>     print 'G'
    21>     return []
    22> def h():
    23>     print 'H'
    24>     return 1
    25>
    26> if a() and b() and  c() and d() or e() and f() or g() and h():
    27>     print 'ok'

    #输出结果如下:
    A
    E
    F
    ok

 

#  別以為語句很長就很難,我們好好分析一下,首先是a() 的邏輯值為False,其後到or 語句為止有三條and 語句: a() and b() and c() and d(),均被短路。得到 a() or e() 為True,輸出 e() ,得 e() and F() 為 True ,輸出 f(), 其後接 or 語句,則短路其後所有。 (結合我總結的短路邏輯的三點好好理解,應該沒問題。)

3. 三元運算運算子

  在python2.5 之前,python 是沒有三元操作符的,Guido Van Rossum 認為它並不能幫助python 更加簡潔,但是那些習慣了c 、 c++ 和java 編程的程式設計師卻嘗試著用and 或or 來模擬出三元運算符,而這利用的就是python的短路邏輯。

  三元運算運算子 bool ? a : b ,若 bool 為真則 a ,否則為 b 。

  转化为 python 语言为:

        bool and a or b

  如何理解呢? 首先 a , b 都为真,这是默认的。如果 bool 为真, 则 bool and a 为真,输出 a ,短路 b 。如果 bool 为假,短路 a,直接 bool or b ,输出 b 。

  换一种更简单的写法:

       return a if bool else b

【相关推荐】

1. Python and、or以及and-or语法总结

2. 解析python中and与or用法

3. 详细介绍Python中and和or实际用法

4. 总结Python的逻辑运算符and

5. Python:逻辑判断与运算符实例

以上是分享python中and / or 的運算邏輯實例教學的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您如何將元素附加到Python列表中?您如何將元素附加到Python列表中?May 04, 2025 am 12:17 AM

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

您如何創建Python列表?舉一個例子。您如何創建Python列表?舉一個例子。May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

討論有效存儲和數值數據的處理至關重要的實際用例。討論有效存儲和數值數據的處理至關重要的實際用例。May 04, 2025 am 12:11 AM

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。1)在金融中,使用内存映射文件和NumPy库可显著提升数据处理速度。2)科研领域,HDF5文件优化数据存储和检索。3)医疗中,数据库优化技术如索引和分区提高数据查询性能。4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显著提升系统性能和可扩展性。

您如何創建Python數組?舉一個例子。您如何創建Python數組?舉一個例子。May 04, 2025 am 12:10 AM

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

使用Shebang系列指定Python解釋器有哪些替代方法?使用Shebang系列指定Python解釋器有哪些替代方法?May 04, 2025 am 12:07 AM

除了shebang線,還有多種方法可以指定Python解釋器:1.直接使用命令行中的python命令;2.使用批處理文件或shell腳本;3.使用構建工具如Make或CMake;4.使用任務運行器如Invoke。每個方法都有其優缺點,選擇適合項目需求的方法很重要。

列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

說明如何將內存分配給Python中的列表與數組。說明如何將內存分配給Python中的列表與數組。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python數組中指定元素的數據類型?您如何在Python數組中指定元素的數據類型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器