深入理解 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)

以上代码返回什么?

实际生产项目踩到的坑,也怪自己没理解到未,才疏学浅!!!

想当然的以为 python 自己会做真值判断了。其实真值判断是在 if 条件语句时会生效,但在普通的 and 的运算符下有另外一个规则。

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.”

“布尔类型是整数类型的一个子类型,在几乎所有的上下文环境中布尔值的行为类似于值0和1,例外的是当转换为字符串时,会分别将字符串”False“或”True“返回。“

就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 运算符有两个操作数,可以是 bool,object,或一个组合

>>> True and True
True

>>> False and False
False

>>> True and False
False

>>> False and True
False

以上示例表明,仅当表达式中的两个操作数都为 true 时,和表达式才返回 True。由于 and 运算符需要两个操作数来构建表达式,因此它是一个二元运算符。

当两边操作书都为 bool 类型时,二元操作运算结果如下。

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

当然,以上的结果也适用于两边操作数一个 bool 表达式的情况。

expression1 and expression2

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

4. 不同类型之间的 and 运算

可以使用 and 运算符在单个表达式中组合两个 Python 对象。在这种情况下,Python 使用内部的bool() 来判断操作数的真值。此时,两个对象之间的运算,结果将获得一个特定的对象,而不是布尔值。仅当给定操作数显式计算为 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]

根据以上测试用例结果,当and运算结果为 False 时返回左操作数,当and运算结果为 True 时返回右操作数

关于真值的判断规则,在 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

以下是对象之间的比较结果集

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

综上:如果 and 表达式中的操作数是对象而不是布尔表达式,则运算符在计算结果为 False 时返回左侧的对象。否则,它将返回右侧的对象,即使其计算最终结果为 False。

⚠️:如果在做对象逻辑运算,最终结果想得到 bool 类型 True/False的话,可以使用内建函数 bool(expression) 将结果重新实例化一下在返回

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

短路操作器,听这个名字就知道是快速运算,Python 的逻辑运算符,如 and and or,使用称为短路求值或惰性求值的东西来加速运算,高效得到结果。

例子:为了确认 and 表达式的最终结果,首先计算左操作数,如果它是False,那么整个表达式都是False。在这种情况下,无需计算右侧的操作数,就已经知道最终结果了

>>> 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 关键字的右侧。这样,如果短路规则生效,则不会运行代价高昂的表达式。
  2. 将更有可能为 false 的表达式放在 and 关键字的左侧。这样, 更有可能通过仅计算左操作数来确定整个表达式是否为 false。

当然,如果一定要执行运算符两边的表达式,则可以使用位运算符号 (&, |, ~),替代逻辑运算符

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

多复杂的组合表达式,最终都可以一重重拆解成一个个独立的小单元,在做合并

就拿开头的引子来说

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

拆成三步来看文章来源地址https://www.toymoban.com/news/detail-699932.html

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

7. 参考

  1. python-and-operator
  2. python-docs-truth-value-testing
  3. Python3 源码阅读 数据类型-Int.md

到了这里,关于深入理解 Python and 逻辑运算符(踩坑)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C++奇迹之旅:深入理解赋值运算符重载

    运算符重载是C++中的一个重要特性,他允许我们为自定义的类型定义自己的运算符行为。通过运算符重载, 我们可以使用与内置数据类型相同的语法来操作自定义类型,从而提高代码的可读性和可维护性 。 还是我们熟悉的日期函数: 然后我们定义两个日期对象d1和d2: 当你想

    2024年04月26日
    浏览(31)
  • Python逻辑运算符、身份运算符查询表

    python的逻辑运算符,在python开发的条件判断中非常有用,这其中涉及到的数学非常基础,就是一个集合的并集、交集、补集的运算。具体的规则如下表: 运算符 描述 实例 and python中布尔“与”,就是求集合运算中的交集 a and b #如果a为False,b不管是True还是False,输出False,两

    2024年02月06日
    浏览(41)
  • 深入理解 SQL UNION 运算符及其应用场景

    SQL UNION 运算符用于组合两个或多个 SELECT 语句的结果集。 每个 UNION 中的 SELECT 语句必须具有相同数量的列。 列的数据类型也必须相似。 每个 SELECT 语句中的列也必须按照相同的顺序排列。 UNION语法 UNION ALL语法 UNION 运算符默认仅选择不同的值。为了允许重复的值,请使用 U

    2024年02月05日
    浏览(49)
  • 【JavaScript】JavaScript 运算符 ④ ( 逻辑运算符 | 逻辑与运算符 && | 逻辑或运算符 || | 逻辑非运算符 ! )

    JavaScript 中的 逻辑运算符 的作用是 对 布尔值 进行运算 , 运算完成 后 的 返回值 也是 布尔值 ; 逻辑运算符 的 使用场景 : 条件控制语句 , 控制程序分支 ; 循环控制语句 , 控制程序循环 ; 逻辑 运算符 列举 : : 逻辑与运算 , 两个操作数都为 true , 最终结果才为 true , 只要有一个操

    2024年03月20日
    浏览(41)
  • Python 中的 `and`, `or`, `not` 运算符:介绍与使用

    Python 中的逻辑运算符 and , or , not 主要用于进行布尔运算。这些运算符非常有用,特别是在条件判断和循环中。 and 运算符用于检查两个(或多个)表达式是否都为 True 。 值得注意的是, and 运算符是短路的,即如果第一个表达式为 False ,则不会检查后面的表达式。 or 运算符

    2024年02月03日
    浏览(42)
  • Verilog HDL按位逻辑运算符及逻辑运算符

    单目按位与运算符 ,运算符后为需要进行逻辑运算的信号,表示对信号进行每位之间相与的操作。例如: reg [3:0] A,C ; assign C = A ; 上面代码等价于 C = A[3] A[2] A[1] A[0] ; 如果A = 4’b0110,C的结果为0 单目按位或运算符 | ,运算符后为需要进行逻辑运算的信号,表示对信号进行每位

    2024年02月16日
    浏览(25)
  • 运算符之算术运算符、关系运算符、逻辑运算符、复合赋值运算符、其他运算符

    运算符是一种告诉编译器执行特定的数学或逻辑操作的符号。C# 有丰富的内置运算符,分类如下: 算术运算符 关系运算符 逻辑运算符 复合赋值运算符 位运算符 其他运算符 运算符优先级(由高到低) 类别 运算符 结合性 后缀 ()[]-.++-- 从左到右 一元 =-!~ ++ -- (type)* sizeof 从

    2024年02月09日
    浏览(44)
  • Python学习笔记:正则表达式、逻辑运算符、lamda、二叉树遍历规则、类的判断

    序号 实例 说明 1 . 匹配任何字符(除换行符以外) 2 d 等效于[0-9],匹配数字 3 D 等效于[^0-9],匹配非数字 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日
    浏览(51)
  • Java逻辑运算符(&&、||和!),Java关系运算符

    逻辑运算符把各个运算的关系表达式连接起来组成一个复杂的逻辑表达式,以判断程序中的表达式是否成立,判断的结果是 true 或 false。 逻辑运算符是对布尔型变量进行运算,其结果也是布尔型,具体如表 1 所示。   表 1 逻辑运算符的用法、含义及实例 运算符 用法 含义 说

    2024年02月03日
    浏览(38)
  • C++ 中的运算符,包括三目运算符,关系和逻辑运算符,地址运算符等等(C++复习向p8)

    加减乘除 ±*/:略 取模运算符 %: 比如 10 % 4=2 自增运算符 ++:给自己加1 自减运算符 —:给自己减1 “==” 是否相等 “!=” 是否不等 “” 是否大于 “” 是否小于 逻辑与,如果2个都是true,条件才true || 逻辑或,两个有一个是true,就是true ! 逻辑非,true变成false,false变成t

    2024年02月07日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包