Python 布尔操作(and/or,Boolean operator)与位操作(&/|,Bitwise operator)
来源:互联网 发布:网络推广属于哪个部门 编辑:程序博客网 时间:2024/05/17 09:34
如标题所言:
- 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 & b2TypeError: unsupported operand type(s) for &: 'list' and 'list'
- 布尔算子支持骤死式(侯捷译,short-circuiting behavior)的评估方式,位操作符不支持:
所谓骤死式
的评估方式,即为一旦该表达式的真假值确定,即使表达式中还有部分尚未检验,整个评估工作仍告结束。
骤死式
的表达方式常用语如下的语句:
if x is not None and x.foo == 42: # ...
如果将这里的 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 66 # 左侧为真, # 接着判断右侧 >>> 0 and 60 # 左侧为假,骤死式, # 不再判断右侧>>> 5 or 65 # 左侧为真,骤死式 # 不在判断右侧>>> 0 or 66 # 左侧为假, # 接着判断右侧
References
[1] Python: Boolean operators vs Bitwise operators
0 0
- Python 布尔操作(and/or,Boolean operator)与位操作(&/|,Bitwise operator)
- 位操作符(bitwise operator)
- python bitwise and or operator VS logical operator
- 操作符(operator)
- Python bitwise operator
- RxJava操作符——条件和布尔操作符(Conditional and Boolean Operators)
- operator=与复制操作
- 函数调用操作符(operator())
- c++ operator(重载操作符)
- C++ operator关键字(重载操作符)
- C++ operator关键字(重载操作符)
- C++ operator关键字(重载操作符)
- 算术操作符(Mathematical operator)
- 关系操作符(relational operator)
- 类型转换操作符(casting operator)
- C++ operator关键字(重载操作符)
- C++ operator关键字(重载操作符)
- C++ operator关键字(重载操作符)
- 跳槽最大原因不是为钱,你信吗?
- pacemaker+drbd主从
- Linux平台Boost的编译方法
- ruby JSON
- 图片的缩、放与自由移动
- Python 布尔操作(and/or,Boolean operator)与位操作(&/|,Bitwise operator)
- 感知机2 -- 随机梯度下降算法
- pacemaker+drbd双主
- Android自定义JsonRequest
- 网页标题栏出现图标的方法
- Sublime Text 3 快捷键总结(拿走)
- val(),html(),text()区别及用法
- 干货分享:分析Android应用使用的技术框架和开源库
- MySQL5.7版本无法启动服务【启动后自动停止】的解决方法