如何在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逻辑或: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'
当你知道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逻辑或: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'