你如何在Python中获得两个变量的逻辑xor?
例如,我有两个我期望成为字符串的变量.我想测试只有其中一个包含True值(不是None或空字符串):
str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
print "ok"
else:
print "bad"
Run Code Online (Sandbox Code Playgroud)
该^运营商似乎是按位,并在所有对象没有定义:
>>> 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'
Run Code Online (Sandbox Code Playgroud) 我有一个python脚本,可以接收零或三个命令行参数.(它可以在默认行为上运行,也可以需要指定所有三个值.)
什么是理想的语法:
if a and (not b or not c) or b and (not a or not c) or c and (not b or not a):
Run Code Online (Sandbox Code Playgroud)
?
在python中,我有一个列表应该只有一个 truthy值(即,bool(value) is True).有没有一种聪明的方法来检查这个?现在,我只是遍历列表并手动检查:
def only1(l)
true_found = False
for v in l:
if v and not true_found:
true_found=True
elif v and true_found:
return False #"Too Many Trues"
return true_found
Run Code Online (Sandbox Code Playgroud)
这似乎不优雅,不是非常pythonic.有更聪明的方法吗?