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

当前回答

Exclusive Or的定义如下

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

其他回答

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'

我知道说这个有点晚了,但我有个想法也许值得,只是作为文档。也许这样可以: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

Xor在Python中是^。它返回:

int型的逐位xor bool的逻辑xor 集合的独占联合 实现__xor__的类的用户定义结果。 TypeError用于未定义的类型,例如字符串或字典。

如果你打算在字符串上使用它们,将它们转换为bool类型可以使你的操作明确(也可以是set(str1) ^ set(str2))。

如果已经将输入规范化为布尔值,则!= = 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