在Python中使用单词and
与&
符号的逻辑或性能是否存在差异?
答案 0 :(得分:6)
and
是一个布尔运算符。它将两个参数视为布尔值,如果它是假的则返回第一个,否则返回第二个。注意,如果第一个是假的,那么第二个参数甚至根本不算计算,这对避免副作用很重要。
示例:
False and True --> False
True and True --> True
1 and 2 --> 2
False and None.explode() --> False
(也不例外) &
有两种行为。
int
,则它计算两个数字的按位AND,返回int
。如果一个是int
且一个是bool
,则bool
值被强制转换为int(为0或1)并且适用相同的逻辑。bool
,则会评估两个参数并返回bool
。TypeError
(例如float & float
等)。示例:
1 & 2 --> 0
1 & True --> 1 & 1 --> 1
True & 2 --> 1 & 2 --> 0
True & True --> True
False & None.explode() --> AttributeError: 'NoneType' object has no attribute 'explode'