如何在Python中获得两个变量的逻辑异或? [英] How do you get the logical xor of two variables in Python?

查看:129
本文介绍了如何在Python中获得两个变量的逻辑异或?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you get the logical xor of two variables in Python?

例如,我有两个我希望是字符串的变量.我想测试其中只有一个包含True值(不是None或空字符串):

For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):

str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
    print "ok"
else:
    print "bad"

^运算符似乎是按位的,并且未在所有对象上定义:

The ^ operator seems to be bitwise, and not defined on all objects:

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

推荐答案

如果您已经将输入归一化为布尔值,则!=为xor.

If you're already normalizing the inputs to booleans, then != is xor.

bool(a) != bool(b)

这篇关于如何在Python中获得两个变量的逻辑异或?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆