你如何在 Python 中获得两个变量的逻辑异或?

新手上路,请多包涵

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

原文由 Zach Hirsch 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 327
2 个回答

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

 bool(a) != bool(b)

原文由 A. Coady 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

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

 bool(a) ^ bool(b)

两个布尔值上的异或运算符是逻辑异或(与整数不同,它是按位的)。 Which makes sense, since bool is just a subclass of int , but is implemented to only have the values 0 and 1 .当域被限制为 01 时,逻辑异或等同于按位异或。

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

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

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

原文由 Zach Hirsch 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏