给定2个int值,如果一个是负数而另一个是正数,则返回True

Mar*_*kas 25 python return logical-operators python-3.x

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!
Run Code Online (Sandbox Code Playgroud)

有人可以解释发生了什么吗?我想做一个班轮:

lambda a, b: (a < 0 != b < 0)
Run Code Online (Sandbox Code Playgroud)

tza*_*man 31

Python中的所有比较运算符都具有相同的优先级.此外,Python确实进行了链接比较.从而,

(a < 0 != b < 0)
Run Code Online (Sandbox Code Playgroud)

分解为:

(a < 0) and (0 != b) and (b < 0)
Run Code Online (Sandbox Code Playgroud)

如果其中任何一个为假,则表达式的总结果为False.

你想要做的是分别评估每个条件,如下所示:

(a < 0) != (b < 0)
Run Code Online (Sandbox Code Playgroud)

其他变种,来自评论:

(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
Run Code Online (Sandbox Code Playgroud)


Eve*_*sle 8

您的代码不能按预期工作,因为!=它的优先级高于a < 0b < 0.正如itzmeontv在他的回答中建议的那样,你可以通过用括号围绕逻辑组件来自己决定优先级:

(a < 0) != (b < 0)
Run Code Online (Sandbox Code Playgroud)

您的代码尝试评估 a < (0 != b) < 0

[编辑]

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

(a < 0) != (b < 0)
Run Code Online (Sandbox Code Playgroud)

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

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

  • 它们实际上是**相同的**优先级; 失败是因为它被视为链式比较.参见[docs](https://docs.python.org/2/reference/expressions.html#not-in). (2认同)

itz*_*nTV 5

你可以用它

return (a < 0) != (b < 0)
Run Code Online (Sandbox Code Playgroud)

比较可以任意链接,例如,x <y <= z等于x <y和y <= z,除了y仅被评估一次(但在两种情况下,当x <y被发现时,根本不评估z是假的).

所以它变成了

(a < 0) and (0 != b) and (b < 0)
Run Code Online (Sandbox Code Playgroud)

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