def logical_xor(a, b): # for example, -1 and 1
print (a < 0) # evaluates to True
print (b < 0) # evaluates to False
print (a < 0 != b < 0) # EVALUATES TO FALSE! why??? it's True != False
return (a < 0 != b < 0) # returns False when it should return True
print ( logical_xor(-1, 1) ) # returns FALSE!
# now for clarification
print ( True != False) # PRINTS TRUE!
有人可以解释发生了什么吗?我试图制作一个班轮:
lambda a, b: (a < 0 != b < 0)
答案 0 :(得分:31)
Python中的所有比较运算符都有same precedence.此外,Python确实进行了链接比较。因此,
(a < 0 != b < 0)
分解为:
(a < 0) and (0 != b) and (b < 0)
如果其中任何一个为假,则表达式的总结果为False
。
您要做的是分别评估每个条件,如下所示:
(a < 0) != (b < 0)
其他变体,来自评论:
(a < 0) is not (b < 0) # True and False are singletons so identity-comparison works
(a < 0) ^ (b < 0) # bitwise-xor does too, as long as both sides are boolean
(a ^ b < 0) # or you could directly bitwise-xor the integers;
# the sign bit will only be set if your condition holds
# this one fails when you mix ints and floats though
(a * b < 0) # perhaps most straightforward, just multiply them and check the sign
答案 1 :(得分:0)
在Python中,比较运算符具有相同的优先级,并且它们是非关联的。对于比较运算符序列,链接规则有一个单独的规则。 Python documentation说明了这一点:
如果
a, b, c, ..., y, z
是表达式且op1, op2, ..., opN
是比较运算符,则op1 b op2 c ... y opN z
等同于a op1 b and b op2 c and ... y opN z
,除了每个表达式最多被评估一次。
此外,a op1 b and b op2 c and ... y opN z
从左到右进行评估。
a < 0 and 0 != b and b < 0
a < 0
将评估为False
,由于short-circuit evaluation,将停止进一步评估。因此,整个表达式将被评估为False
。