在Python中,如何得到两个变量的逻辑xor?

2024-03-29 12:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python中获得两个变量的logical xor

例如,我有两个变量,我希望它们是字符串。我想测试其中只有一个包含真值(不是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'

Tags: 字符串noneinputstringrawoneprintenter
1条回答
网友
1楼 · 发布于 2024-03-29 12:25:03

您始终可以使用xor的定义从其他逻辑操作计算它:

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

但这对我来说有点太冗长了,乍一看也不是特别清楚。另一种方法是:

bool(a) ^ bool(b)

两个布尔上的xor运算符是逻辑xor(与int上的不同,后者是按位的)。这是有意义的,因为^{} is just a subclass of ^{},但是实现时只有值01。当域被限制在01时,逻辑异或等价于按位异或。

因此logical_xor函数的实现方式如下:

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

记入Nick Coghlan on the Python-3000 mailing list

网友
2楼 · 发布于 2024-03-29 12:25:03

如果您已经将输入规范化为布尔型,那么!=是异或。

bool(a) != bool(b)
网友
3楼 · 发布于 2024-03-29 12:25:03

异或已内置到Python的^{}模块中(与^运算符相同):

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

相关问题 更多 >