给定 2 个 int 值,return 如果一个为负而另一个为正则为真

Given 2 int values, return True if one is negative and other is positive

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)

你可以使用这个

return (a < 0) != (b < 0)

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

于是就变成了

(a < 0) and (0 != b) and (b < 0)

https://docs.python.org/3/reference/expressions.html#not-in

您的代码没有按预期工作,因为 !=a < 0b < 0 占用更高的 precedence。正如 itzmeontv 在他的回答中所建议的那样,您可以通过用括号括起逻辑组件来自己决定优先级:

(a < 0) != (b < 0)

您的代码尝试计算 a < (0 != b) < 0

[编辑]

正如 tzaman 正确指出的那样,运算符具有相同的优先级,但您的代码正在尝试评估 (a < 0) and (0 != b) and (b < 0)。用括号包围你的逻辑组件将解决这个问题:

(a < 0) != (b < 0)

运算符优先级:https://docs.python.org/3/reference/expressions.html#operator-precedence

比较(i.a。链接):https://docs.python.org/3/reference/expressions.html#not-in

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

在Python中,比较运算符具有相同的优先级,并且它们是非结合的。比较运算符的序列有一个单独的规则,即链接规则。 Python documentation 声明:

if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

此外,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.