如何在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表达式«is not»,以获得逻辑«xor»的行为

真值表是:

>>> True is not True
False
>>> True is not False
True
>>> False is not True
True
>>> False is not False
False
>>>

对于你的例子字符串:

>>> "abc" is not  ""
True
>>> 'abc' is not 'abc' 
False
>>> 'abc' is not '' 
True
>>> '' is not 'abc' 
True
>>> '' is not '' 
False
>>> 

然而;正如上面所指出的,这取决于你想要抽出任意一对字符串的实际行为,因为字符串不是bolean…甚至更多:如果你«潜入Python»你会发现«“and”和“or”的特殊性质» http://www.diveintopython.net/power_of_introspection/and_or.html

抱歉我的书面英语,它不是我天生的语言。

的问候。

其他回答

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

bool(a) != bool(b)

正如Zach解释的那样,你可以使用:

xor = bool(a) ^ bool(b)

就我个人而言,我喜欢一种略有不同的方言:

xor = bool(a) + bool(b) == 1

这种方言的灵感来自我在学校学习的一种逻辑图表语言,其中“OR”用一个包含≥1(大于或等于1)的方框表示,“XOR”用一个包含=1的方框表示。

这样做的优点是可以正确地实现独占或多个操作数。

"1 = a ^ b ^ c…"意思是真操作数的个数是奇数。这个运算符就是“奇偶校验”。 "1 = a + b + c…"意味着只有一个操作数为真。这是“排他的或”,意思是“一个排除其他的”。

简单,容易理解:

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

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

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

因为我没有看到xor的简单变体使用变量参数,只对真值True或False进行操作,所以我只是把它扔在这里供任何人使用。 正如其他人所指出的,这相当(不是非常)直接。

def xor(*vars):
    result = False
    for v in vars:
        result = result ^ bool(v)
    return result

用法也很简单:

if xor(False, False, True, False):
    print "Hello World!"

由于这是广义n元逻辑异或,当True操作数的数量为奇数时,它的真值将为True(不仅仅是当恰好有一个为True时,这只是n元异或为True的一种情况)。

因此,如果你在搜索一个n-ary谓词,当它的一个操作数恰好为True时,它才为True,你可能想使用:

def isOne(*vars):
    result = False
    for v in vars:
        if result and v:
            return False
        else:
            result = result or v
    return result

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

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

例子:

xor(真,假)>>真