如何在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在operator.xor中实现。

因为我没有看到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

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

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

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

bool(a) ^ bool(b)

(编辑-谢谢雷尔)

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

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

这将获得两个(或多个)变量的逻辑独占异或

str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")

any([str1, str2]) and not all([str1, str2])

这种设置的第一个问题是,它很可能遍历整个列表两次,并且至少会检查至少一个元素两次。因此,它可以提高代码的理解能力,但不能提高速度(根据您的用例,速度可能略有不同)。

这种设置的第二个问题是,无论变量的数量如何,它都会检查排他性。这可能一开始被认为是一个特征,但随着变量数量的增加,第一个问题变得更加重要(如果它们确实如此的话)。