国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

深入理解 Python and 邏輯運算符(踩坑)

這篇具有很好參考價值的文章主要介紹了深入理解 Python and 邏輯運算符(踩坑)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

深入理解 Python and 邏輯運算符(踩坑)

1. 引子

def enabled() -> bool:
    a = ["a,"b"]
	b = True
    c = False
    return (b and c) or (b and a)

以上代碼返回什么?

實際生產(chǎn)項目踩到的坑,也怪自己沒理解到未,才疏學(xué)淺?。?!

想當然的以為 python 自己會做真值判斷了。其實真值判斷是在 if 條件語句時會生效,但在普通的 and 的運算符下有另外一個規(guī)則。

2. python bool 類型簡述

“The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings ‘False’ or ‘True’ are returned, respectively.”

“布爾類型是整數(shù)類型的一個子類型,在幾乎所有的上下文環(huán)境中布爾值的行為類似于值0和1,例外的是當轉(zhuǎn)換為字符串時,會分別將字符串”False“或”True“返回?!?/p>

就python而言,True,1和1.0都表示相同的字典鍵

>>> True == 1 == 1.0
True
>>> (hash(True), hash(1), hash(1.0))
(1, 1, 1)

>>> issubclass(bool, int)
True
>>> isinstance(True, int)
True
>>> isinstance(False, int)
True
>>> int(True)
1
>>> int(False)
0

>>> help(bool)

Help on class bool in module builtins:

class bool(int)
    |  bool(x) -> bool
    |
    |  Returns True when the argument x is true, False otherwise.
        |  The builtins True and False are the only two instances of the class bool.
        |  The class bool is a subclass of the class int, and cannot be subclassed.

3. bool類型之間的 and 運算

and 運算符有兩個操作數(shù),可以是 bool,object,或一個組合

>>> True and True
True

>>> False and False
False

>>> True and False
False

>>> False and True
False

以上示例表明,僅當表達式中的兩個操作數(shù)都為 true 時,和表達式才返回 True。由于 and 運算符需要兩個操作數(shù)來構(gòu)建表達式,因此它是一個二元運算符。

當兩邊操作書都為 bool 類型時,二元操作運算結(jié)果如下。

operand1 operand2 operand1 and operand2
True True True
True False False
False False False
False True False

當然,以上的結(jié)果也適用于兩邊操作數(shù)一個 bool 表達式的情況。

expression1 and expression2

>>> 5>3 and 5==3+2
True

4. 不同類型之間的 and 運算

可以使用 and 運算符在單個表達式中組合兩個 Python 對象。在這種情況下,Python 使用內(nèi)部的bool() 來判斷操作數(shù)的真值。此時,兩個對象之間的運算,結(jié)果將獲得一個特定的對象,而不是布爾值。僅當給定操作數(shù)顯式計算為 True 或 False 時,才會獲得 True 或 False

>>> 2 and 3
3
>>> 5 and 0.0
0.0
>>> [] and 3
[]
>>> 0 and {}
0
>>> 1 and {}
{}
>>> False and ""
False
>>> True and ""
''
>>> ["a"] and [1]
[1]

根據(jù)以上測試用例結(jié)果,當and運算結(jié)果為 False 時返回左操作數(shù),當and運算結(jié)果為 True 時返回右操作數(shù)

關(guān)于真值的判斷規(guī)則,在 python 的文檔中有說明

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object. 1 Here are most of the built-in objects considered false:

  • constants defined to be false: None and False
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • empty sequences and collections: '', (), [], {}, set(), range(0)

https://docs.python.org/3/library/stdtypes.html#truth-value-testing

以下是對象之間的比較結(jié)果集

object1 object2 object1 and object2
False False object1
False True object1
True True object2
True False object2

綜上:如果 and 表達式中的操作數(shù)是對象而不是布爾表達式,則運算符在計算結(jié)果為 False 時返回左側(cè)的對象。否則,它將返回右側(cè)的對象,即使其計算最終結(jié)果為 False。

??:如果在做對象邏輯運算,最終結(jié)果想得到 bool 類型 True/False的話,可以使用內(nèi)建函數(shù) bool(expression) 將結(jié)果重新實例化一下在返回

5. 高效運算-“快速短路”(short-circuit operator)

短路操作器,聽這個名字就知道是快速運算,Python 的邏輯運算符,如 and and or,使用稱為短路求值或惰性求值的東西來加速運算,高效得到結(jié)果。

例子:為了確認 and 表達式的最終結(jié)果,首先計算左操作數(shù),如果它是False,那么整個表達式都是False。在這種情況下,無需計算右側(cè)的操作數(shù),就已經(jīng)知道最終結(jié)果了

>>> def true_func():
...     print("Running true_func()")
...     return True
...

>>> def false_func():
...     print("Running false_func()")
...     return False
...

>>> true_func() and false_func()  # Case 1
Running true_func()
Running false_func()
False

>>> false_func() and true_func()  # Case 2
Running false_func()
False

>>> false_func() and false_func()  # Case 3
Running false_func()
False

>>> true_func() and true_func()  # Case 4
Running true_func()
Running true_func()
True

短路操作器,是提升代碼性能的一種有效手段。在邏輯運算表達式時,可考慮如下兩個原則:

  1. 將耗時的表達式放在 and 關(guān)鍵字的右側(cè)。這樣,如果短路規(guī)則生效,則不會運行代價高昂的表達式。
  2. 將更有可能為 false 的表達式放在 and 關(guān)鍵字的左側(cè)。這樣, 更有可能通過僅計算左操作數(shù)來確定整個表達式是否為 false。

當然,如果一定要執(zhí)行運算符兩邊的表達式,則可以使用位運算符號 (&, |, ~),替代邏輯運算符

>>> def true_func():
...     print("Running true_func()")
...     return True
...

>>> def false_func():
...     print("Running false_func()")
...     return False
...

>>> # Use logical and
>>> false_func() and true_func()
Running false_func()
False

>>> # Use bitwise and
>>> false_func() & true_func()
Running false_func()
Running true_func()
False

6. bool 邏輯運算的萬能公式

Operation Result Notes
法則 1 x or y if x is true, then x, else y 1
法則 2 x and y if x is false, then x, else y 2
法則 3 not x if x is false, then True, else False 3

Notes:

  1. This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
  2. This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
  3. not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

多復(fù)雜的組合表達式,最終都可以一重重拆解成一個個獨立的小單元,在做合并

就拿開頭的引子來說

def enabled() -> bool:
    a = ["a,"b"]
	b = True
    c = False
    return (b and c) or (b and a)

拆成三步來看文章來源地址http://www.zghlxwxcb.cn/news/detail-699932.html

  1. b and c --> 運用法則 2 (if x is false, then x, else y) 所以結(jié)果是 c 即 False
  2. b and a --> a 運用法則 2 (if x is false, then x, else y) 所以結(jié)果是 a 即 ["a", "b"]
  3. False or ["a", "b"] 運用法則 1 (if x is true, then x, else y) 所以結(jié)果是 ["a", "b"]

7. 參考

  1. python-and-operator
  2. python-docs-truth-value-testing
  3. Python3 源碼閱讀 數(shù)據(jù)類型-Int.md

到了這里,關(guān)于深入理解 Python and 邏輯運算符(踩坑)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • C++奇跡之旅:深入理解賦值運算符重載

    C++奇跡之旅:深入理解賦值運算符重載

    運算符重載是C++中的一個重要特性,他允許我們?yōu)樽远x的類型定義自己的運算符行為。通過運算符重載, 我們可以使用與內(nèi)置數(shù)據(jù)類型相同的語法來操作自定義類型,從而提高代碼的可讀性和可維護性 。 還是我們熟悉的日期函數(shù): 然后我們定義兩個日期對象d1和d2: 當你想

    2024年04月26日
    瀏覽(20)
  • Python邏輯運算符、身份運算符查詢表

    python的邏輯運算符,在python開發(fā)的條件判斷中非常有用,這其中涉及到的數(shù)學(xué)非?;A(chǔ),就是一個集合的并集、交集、補集的運算。具體的規(guī)則如下表: 運算符 描述 實例 and python中布爾“與”,就是求集合運算中的交集 a and b #如果a為False,b不管是True還是False,輸出False,兩

    2024年02月06日
    瀏覽(23)
  • 深入理解 SQL UNION 運算符及其應(yīng)用場景

    深入理解 SQL UNION 運算符及其應(yīng)用場景

    SQL UNION 運算符用于組合兩個或多個 SELECT 語句的結(jié)果集。 每個 UNION 中的 SELECT 語句必須具有相同數(shù)量的列。 列的數(shù)據(jù)類型也必須相似。 每個 SELECT 語句中的列也必須按照相同的順序排列。 UNION語法 UNION ALL語法 UNION 運算符默認僅選擇不同的值。為了允許重復(fù)的值,請使用 U

    2024年02月05日
    瀏覽(28)
  • 【JavaScript】JavaScript 運算符 ④ ( 邏輯運算符 | 邏輯與運算符 && | 邏輯或運算符 || | 邏輯非運算符 ! )

    【JavaScript】JavaScript 運算符 ④ ( 邏輯運算符 | 邏輯與運算符 && | 邏輯或運算符 || | 邏輯非運算符 ! )

    JavaScript 中的 邏輯運算符 的作用是 對 布爾值 進行運算 , 運算完成 后 的 返回值 也是 布爾值 ; 邏輯運算符 的 使用場景 : 條件控制語句 , 控制程序分支 ; 循環(huán)控制語句 , 控制程序循環(huán) ; 邏輯 運算符 列舉 : : 邏輯與運算 , 兩個操作數(shù)都為 true , 最終結(jié)果才為 true , 只要有一個操

    2024年03月20日
    瀏覽(34)
  • Python 中的 `and`, `or`, `not` 運算符:介紹與使用

    Python 中的 `and`, `or`, `not` 運算符:介紹與使用

    Python 中的邏輯運算符 and , or , not 主要用于進行布爾運算。這些運算符非常有用,特別是在條件判斷和循環(huán)中。 and 運算符用于檢查兩個(或多個)表達式是否都為 True 。 值得注意的是, and 運算符是短路的,即如果第一個表達式為 False ,則不會檢查后面的表達式。 or 運算符

    2024年02月03日
    瀏覽(29)
  • Verilog HDL按位邏輯運算符及邏輯運算符

    單目按位與運算符 ,運算符后為需要進行邏輯運算的信號,表示對信號進行每位之間相與的操作。例如: reg [3:0] A,C ; assign C = A ; 上面代碼等價于 C = A[3] A[2] A[1] A[0] ; 如果A = 4’b0110,C的結(jié)果為0 單目按位或運算符 | ,運算符后為需要進行邏輯運算的信號,表示對信號進行每位

    2024年02月16日
    瀏覽(29)
  • 運算符之算術(shù)運算符、關(guān)系運算符、邏輯運算符、復(fù)合賦值運算符、其他運算符

    運算符是一種告訴編譯器執(zhí)行特定的數(shù)學(xué)或邏輯操作的符號。C# 有豐富的內(nèi)置運算符,分類如下: 算術(shù)運算符 關(guān)系運算符 邏輯運算符 復(fù)合賦值運算符 位運算符 其他運算符 運算符優(yōu)先級(由高到低) 類別 運算符 結(jié)合性 后綴 ()[]-.++-- 從左到右 一元 =-!~ ++ -- (type)* sizeof 從

    2024年02月09日
    瀏覽(28)
  • Python學(xué)習(xí)筆記:正則表達式、邏輯運算符、lamda、二叉樹遍歷規(guī)則、類的判斷

    Python學(xué)習(xí)筆記:正則表達式、邏輯運算符、lamda、二叉樹遍歷規(guī)則、類的判斷

    序號 實例 說明 1 . 匹配任何字符(除換行符以外) 2 d 等效于[0-9],匹配數(shù)字 3 D 等效于[^0-9],匹配非數(shù)字 4 s 等效于[trnf],匹配空格字符 5 S 等效于[^trnf],匹配非空格字符 6 w 等效于[A-Za-z0-9],匹配單字字符 7 W 等效于[^A-Za-z0-9],匹配非單字字符 8 [ab]cdef 匹配acdef或bcd

    2024年02月11日
    瀏覽(60)
  • Java邏輯運算符(&&、||和!),Java關(guān)系運算符

    Java邏輯運算符(&&、||和!),Java關(guān)系運算符

    邏輯運算符把各個運算的關(guān)系表達式連接起來組成一個復(fù)雜的邏輯表達式,以判斷程序中的表達式是否成立,判斷的結(jié)果是 true 或 false。 邏輯運算符是對布爾型變量進行運算,其結(jié)果也是布爾型,具體如表 1 所示。 ? 表 1 邏輯運算符的用法、含義及實例 運算符 用法 含義 說

    2024年02月03日
    瀏覽(23)
  • C++ 中的運算符,包括三目運算符,關(guān)系和邏輯運算符,地址運算符等等(C++復(fù)習(xí)向p8)

    加減乘除 ±*/:略 取模運算符 %: 比如 10 % 4=2 自增運算符 ++:給自己加1 自減運算符 —:給自己減1 “==” 是否相等 “!=” 是否不等 “” 是否大于 “” 是否小于 邏輯與,如果2個都是true,條件才true || 邏輯或,兩個有一個是true,就是true ! 邏輯非,true變成false,false變成t

    2024年02月07日
    瀏覽(35)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包