如何在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处理逻辑操作的方式可能令人困惑,因此我的实现为用户提供了一个简单的True/False答案选项(默认情况下)。实际的Python结果可以通过将可选的第三个参数设置为None来获得。

def xor(a, b, true=True, false=False): # set true to None to get actual Python result
    ab1 = a and not b
    ab2 = not a and b
    if bool(ab1) != bool(ab2):
        return (ab1 or ab2) if true is None else true
    else:
        return false

其他回答

Python处理逻辑操作的方式可能令人困惑,因此我的实现为用户提供了一个简单的True/False答案选项(默认情况下)。实际的Python结果可以通过将可选的第三个参数设置为None来获得。

def xor(a, b, true=True, false=False): # set true to None to get actual Python result
    ab1 = a and not b
    ab2 = not a and b
    if bool(ab1) != bool(ab2):
        return (ab1 or ab2) if true is None else true
    else:
        return false

奖励线程:

阳极的想法……您只需尝试(可能是)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

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

的问候。

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'

假设A和B是bool。

A is not B

这就是我编写真值表的方法。对于xor,我们有:

| a | b  | xor   |             |
|---|----|-------|-------------|
| T | T  | F     |             |
| T | F  | T     | a and not b |
| F | T  | T     | not a and b |
| F | F  | F     |             |

看看答案列中的T值,用逻辑上的或将所有真情况串在一起。所以,这个真值表可以在情况2或3中产生。因此,

xor = lambda a, b: (a and not b) or (not a and b)