是&和< and>等价于python? [英] Are & and <and> equivalent in python?
本文介绍了是&和< and>等价于python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中使用和
一词与&
符号的逻辑或性能是否存在差异?
Is there any difference in the logic or performance of using the word and
vs. the &
symbol in Python?
推荐答案
and
是布尔运算符.它将两个参数都视为布尔值,如果错误则返回第一个,否则返回第二个.请注意,如果第一个参数是虚假的,那么第二个参数甚至都不会计算,这对于避免副作用很重要.
and
is a Boolean operator. It treats both arguments as Boolean values, returning the first if it's falsy, otherwise the second. Note that if the first is falsy, then the second argument isn't even computed at all, which is important for avoiding side effects.
示例:
-
False和True->错误
-
True and True->正确
-
1和2->2
-
False和None.explode()->错误
(也不例外)
False and True --> False
True and True --> True
1 and 2 --> 2
False and None.explode() --> False
(no exception)
&
具有两种行为.
- 如果两个都是
int
,则它将计算两个数字的按位与,并返回一个int
.如果一个是int
,一个是bool
,则将bool
的值强制转换为int(为0或1),并且应用相同的逻辑. - 否则,如果两个都是
bool
,则将评估两个参数并返回bool
. - 否则会引发
TypeError
(例如float& float
等).
- If both are
int
, then it computes the bitwise AND of both numbers, returning anint
. If one isint
and one isbool
, then thebool
value is coerced to int (as 0 or 1) and the same logic applies. - Else if both are
bool
, then both arguments are evaluated and abool
is returned. - Otherwise a
TypeError
is raised (such asfloat & float
, etc.).
示例:
-
1&2->0
-
1&正确->1&1->1
-
True&2->1&2->0
-
True&正确->正确
-
False&None.explode()->AttributeError:'NoneType'对象没有属性'explode'
这篇关于是&和< and>等价于python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文