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

当前回答

很多人,包括我自己,都需要一个类似于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

其他回答

这个怎么样?

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

如果b为假会给出a 如果a为假,会给出b 否则会返回False

或者使用Python 2.5+三元表达式:

(False if a else b) if b else a

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

这是映射-缩减泛化的实现。注意,这相当于functools。Reduce (lambda x, y: x != y, map(bool, orands))。

def xor(*orands):
    return bool(sum(bool(x) for x in orands) % 2)

如果你在寻找一个单一热点探测器,这是一个概括。这种概括可能适用于英语中exclusive-or的用法(例如:“花一美元,你可以买一杯果汁、咖啡或茶”),但这与典型的操作顺序不符。E.g.xor_1hot (1 1 1) = = 0 ! = 1 = = xor_1hot (xor_1hot(1, 1), 1)。

def xor_1hot(*orands):
    return sum(bool(x) for x in orands) == 1

你可以用

# test
from itertools import product
n = 3
total_true = 0
for inputs in product((False, True), repeat=n):
    y = xor(*inputs)
    total_true += int(y)
    print(f"{''.join(str(int(b)) for b in inputs)}|{y}")
print('Total True:', total_true)

单热检测器输出:

000 |假 001 |真 010 |真 011 |假 100 |真 101 |假 110 |假 111 |假 总数正确:3

使用映射-规约模式输出:

000 |假 001 |真 010 |真 011 |假 100 |真 101 |假 110 |假 111 |真 总数:4

你总是可以使用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。

简单,容易理解:

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

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

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