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

当前回答

Exclusive Or的定义如下

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

其他回答

奖励线程:

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

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

的问候。

这里建议的一些实现在某些情况下会导致操作数的重复求值,这可能会导致意想不到的副作用,因此必须避免。

也就是说,一个返回True或False的xor实现相当简单;如果可能的话,返回其中一个操作数的方法要棘手得多,因为对于应该选择哪个操作数没有共识,特别是当有两个以上的操作数时。例如,xor(None, -1, [], True)是否应该返回None,[]或False?我敢打赌,每个答案对某些人来说都是最直观的。

对于True-或false -结果,有多达五种可能的选择:返回第一个操作数(如果它在value中匹配最终结果,否则布尔值),返回第一个匹配(如果至少存在一个,否则布尔值),返回最后一个操作数(如果…Else…),返回最后一次匹配(if…Else…),或者总是返回boolean。总共是5 ** 2 = 25种xor口味。

def xor(*operands, falsechoice = -2, truechoice = -2):
  """A single-evaluation, multi-operand, full-choice xor implementation
  falsechoice, truechoice: 0 = always bool, +/-1 = first/last operand, +/-2 = first/last match"""
  if not operands:
    raise TypeError('at least one operand expected')
  choices = [falsechoice, truechoice]
  matches = {}
  result = False
  first = True
  value = choice = None
  # avoid using index or slice since operands may be an infinite iterator
  for operand in operands:
    # evaluate each operand once only so as to avoid unintended side effects
    value = bool(operand)
    # the actual xor operation
    result ^= value
    # choice for the current operand, which may or may not match end result
    choice = choices[value]
    # if choice is last match;
    # or last operand and the current operand, in case it is last, matches result;
    # or first operand and the current operand is indeed first;
    # or first match and there hasn't been a match so far
    if choice < -1 or (choice == -1 and value == result) or (choice == 1 and first) or (choice > 1 and value not in matches):
      # store the current operand
      matches[value] = operand
    # next operand will no longer be first
    first = False
  # if choice for result is last operand, but they mismatch
  if (choices[result] == -1) and (result != value):
    return result
  else:
    # return the stored matching operand, if existing, else result as bool
    return matches.get(result, result)

testcases = [
  (-1, None, True, {None: None}, [], 'a'),
  (None, -1, {None: None}, 'a', []),
  (None, -1, True, {None: None}, 'a', []),
  (-1, None, {None: None}, [], 'a')]
choices = {-2: 'last match', -1: 'last operand', 0: 'always bool', 1: 'first operand', 2: 'first match'}
for c in testcases:
  print(c)
  for f in sorted(choices.keys()):
    for t in sorted(choices.keys()):
      x = xor(*c, falsechoice = f, truechoice = t)
      print('f: %d (%s)\tt: %d (%s)\tx: %s' % (f, choices[f], t, choices[t], x))
  print()

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'

这个怎么样?

(not b and a) or (not a and b)

如果b为假会给出a 如果a为假,会给出b 否则会返回False

或者使用Python 2.5+三元表达式:

(False if a else b) if b else a

你总是可以使用xor的定义从其他逻辑操作中计算它:

(a and not b) or (not a and b)

但这对我来说有点太啰嗦了,而且乍一看不是特别清楚。另一种方法是:

bool(a) ^ bool(b)

两个布尔值上的xor操作符是逻辑xor(不像整型值上的xor,它是按位的)。这是有意义的,因为bool只是int的一个子类,但被实现为只有值0和1。当域限制为0和1时,逻辑xor等价于按位xor。

所以logical_xor函数的实现方式如下:

def logical_xor(str1, str2):
    return bool(str1) ^ bool(str2)

感谢Python-3000邮件列表中的Nick Coghlan。