Python 布尔操作(and/or,Boolean operator)与位操作( /|,Bitwise operato

分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net

如标题所言:

  • and(or):boolean operator
  • &(|):bitwise operator

二者的主要区别在于:

  • boolean 算子(and/or)主要用于布尔值(True/False),而位操作子(bitwise operator,&/|)通常用于整型之间
>>> b1 = [True, True, True, False, True]
>>> b2 = [False, True, False, True, False]

>>> b1 and b2
[False, True, False, True, False]

>>> b1 & b2
TypeError: unsupported operand type(s) for &: 'list' and 'list'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 布尔算子支持骤死式(侯捷译,short-circuiting behavior)的评估方式,位操作符不支持:

所谓骤死式的评估方式,即为一旦该表达式的真假值确定,即使表达式中还有部分尚未检验,整个评估工作仍告结束。

骤死式的表达方式常用语如下的语句:

if x is not None and x.foo == 42:
    # ...
  • 1
  • 2

如果将这里的 and 换成 &,将会导致不必要的异常(AttributeError: 'NoneType' object has no attribute 'foo',如果 x is not None不成立),因为对 & 而言,&两边都要被评估。

  • When you use the boolean and operator the second expression is not evaluated when the first is False. (当使用 and 算子时,如果左侧判断为假,将不会判断右侧的语句的真假,因为是徒劳的,无论第二条语句为真还是为假,结果总是为假)

  • Similarly or does not evaluate the second argument if the first is True.(当使用 or 算子时,如果左侧判断为真,将不会判断右侧语句的真假,因为也是徒劳的,即无论第二条语句为真还是为假,结果总为真)

>>> 5 and 6
6
                    # 左侧为真,
                    # 接着判断右侧        
>>> 0 and 6
0
                    # 左侧为假,骤死式,
                    # 不再判断右侧
>>> 5 or 6
5
                    # 左侧为真,骤死式
                    # 不在判断右侧
>>> 0 or 6
6
                    # 左侧为假,
                    # 接着判断右侧
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

References

[1] Python: Boolean operators vs Bitwise operators

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net

猜你喜欢

转载自www.cnblogs.com/siwnhwxh/p/10523138.html