如何在Python中获得两个变量的逻辑异或?

例如,我有两个变量,我希望它们是字符串。我想测试它们中只有一个包含True值(不是None或空字符串):

str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
    print "ok"
else:
    print "bad"

^操作符似乎是按位的,并不是在所有对象上都定义:

>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'str' and 'str'

当前回答

Python逻辑或:A或B:如果bool(A)为True则返回A,否则返回B Python逻辑和:A和B:如果bool(A)为False则返回A,否则返回B

为了保持这种思维方式,我的逻辑xor定义将是:

def logical_xor(a, b):
    if bool(a) == bool(b):
        return False
    else:
        return a or b

这样它就可以返回a, b或False:

>>> logical_xor('this', 'that')
False
>>> logical_xor('', '')
False
>>> logical_xor('this', '')
'this'
>>> logical_xor('', 'that')
'that'

其他回答

只是因为我没有在其他地方看到过它,这也是一个诀窍:

def logical_xor(a, b):
    return not b if a else bool(b)

我不确定它是否比公认的解决方案bool(a) != bool(b)“更好”/更可读/更python化。

如果已经将输入规范化为布尔值,则!= = xor。

bool(a) != bool(b)

我知道说这个有点晚了,但我有个想法也许值得,只是作为文档。也许这样可以:np.abs(x-y

如果x=True=1和y=False=0,那么结果将是|1-0|=1=True 如果x=False=0和y=False=0,那么结果将是|0-0|=0=False 如果x=True=1和y=True=1,那么结果将是|1-1|=0=False 如果x=False=0和y=True=1,那么结果将是|0-1|=1=True

在Python中获取两个或多个变量的逻辑异或:

将输入转换为布尔值 使用按位的异或操作符(^ or operator.xor)

例如,

bool(a) ^ bool(b)

当您将输入转换为布尔值时,按位xor变成逻辑xor。

请注意,接受的答案是错误的:!=与Python中的xor不同,因为操作符链接非常微妙。

例如,下面三个值的xor在使用!=时是错误的:

True ^  False ^  False  # True, as expected of XOR
True != False != False  # False! Equivalent to `(True != False) and (False != False)`

(附注:我尝试编辑已接受的答案,以包含这一警告,但我的更改被拒绝了。)

简单,容易理解:

sum(bool(a), bool(b)) == 1

如果一个排他性的选项是你想要的,即从n个选项中选择1个,它可以扩展为多个参数:

sum(bool(x) for x in y) == 1