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

当前回答

这个怎么样?

(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:

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

例子:

xor(真,假)>>真

奖励线程:

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

| 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)

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

bool(a) != bool(b)

很多人,包括我自己,都需要一个类似于n输入异或电路的异或函数,其中n是变量。(见https://en.wikipedia.org/wiki/XOR_gate)。下面的简单函数实现了这一点。

def xor(*args):
   """
   This function accepts an arbitrary number of input arguments, returning True
   if and only if bool() evaluates to True for an odd number of the input arguments.
   """

   return bool(sum(map(bool,args)) % 2)

示例I/O如下:

In [1]: xor(False, True)
Out[1]: True

In [2]: xor(True, True)
Out[2]: False

In [3]: xor(True, True, True)
Out[3]: True