相关疑难解决方法(0)

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

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

597
推荐指数
21
解决办法
65万
查看次数

"如果a或b或c但不是全部"的Python语法

我有一个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 if-statement

128
推荐指数
10
解决办法
19万
查看次数

如何检查列表是否只有一个真值?

在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.有更聪明的方法吗?

python

76
推荐指数
8
解决办法
2万
查看次数

标签 统计

python ×3

if-statement ×1

logical-operators ×1