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

其他回答

我们可以很容易地找到两个变量的xor:

def xor(a,b):
    return a !=b

例子:

xor(真,假)>>真

当你知道XOR是做什么的时候就很简单了:

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

test_data = [
  [False, False],
  [False, True],
  [True, False],
  [True, True],
]

for a, b in test_data:
    print '%r xor %s = %r' % (a, b, logical_xor(a, b))

在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)`

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

这是映射-缩减泛化的实现。注意,这相当于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

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

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

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

bool(a) ^ bool(b)

(编辑-谢谢雷尔)