如何在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'

当前回答

有时我发现自己使用1和0而不是布尔值True和False。在这种情况下,xor可以定义为

z = (x + y) % 2

它有如下的真值表:

     x
   |0|1|
  -+-+-+
  0|0|1|
y -+-+-+
  1|1|0|
  -+-+-+

其他回答

Python有一个逐位的异或运算符,它是^:

>>> True ^ False
True
>>> True ^ True
False
>>> False ^ True
True
>>> False ^ False
False

你可以在应用xor(^)之前将输入转换为布尔值来使用它:

bool(a) ^ bool(b)

(编辑-谢谢雷尔)

很多人,包括我自己,都需要一个类似于n输入异或电路的异或函数,其中n是变量。(见https://en.wikipedia.org/wiki/XOR_gate)。下面的简单函数实现了这一点。

def xor(*args):
   """
   This function accepts an arbitrary number of input arguments, returning True
   if and only if bool() evaluates to True for an odd number of the input arguments.
   """

   return bool(sum(map(bool,args)) % 2)

示例I/O如下:

In [1]: xor(False, True)
Out[1]: True

In [2]: xor(True, True)
Out[2]: False

In [3]: xor(True, True, True)
Out[3]: True

Exclusive Or的定义如下

def xor( a, b ):
    return (a or b) and not (a and b)

你总是可以使用xor的定义从其他逻辑操作中计算它:

(a and not b) or (not a and b)

但这对我来说有点太啰嗦了,而且乍一看不是特别清楚。另一种方法是:

bool(a) ^ bool(b)

两个布尔值上的xor操作符是逻辑xor(不像整型值上的xor,它是按位的)。这是有意义的,因为bool只是int的一个子类,但被实现为只有值0和1。当域限制为0和1时,逻辑xor等价于按位xor。

所以logical_xor函数的实现方式如下:

def logical_xor(str1, str2):
    return bool(str1) ^ bool(str2)

感谢Python-3000邮件列表中的Nick Coghlan。

按位异或已经内置在Python的operator模块中(与^ operator相同):

from operator import xor
xor(bool(a), bool(b))  # Note: converting to bools is essential