我喜欢在 Python 中使用any()and 。all()但有时我需要一个one().
我想知道列表中是否只有一个True值或条件是.
目前我用这样一个嵌套的丑陋来做到这一点if。
# In real world there could be more then just two elements
istrue = [True, False]
isfalse = [True, 'foobar']
isfalse2 = [False, False]
def one(values):
if values[0] and values[1]:
return False
if not values[0] and not values[1]:
return False
return True
one(istrue) # True
one(isfalse) # False
one(isfalse2) # False
Run Code Online (Sandbox Code Playgroud)
我认为有一种更Pythonic的方式,不是吗?
sum(map(bool, l)) == 1
Run Code Online (Sandbox Code Playgroud)
这可能是最短的表达方式了。它将列表中的每个项目转换为布尔值,并对它们求和。真值将计为1,假值将计为0。因此,如果总和恰好为1,则其中恰好有一个真实项。
all如果您想要/的短路行为any,以避免不必要地迭代所有项目,那么如下所示:
def one(l):
truthy = 0
for i in l:
truthy += bool(i)
if truthy > 1:
return False
return truthy == 1
Run Code Online (Sandbox Code Playgroud)
将所有元素转换为布尔值,然后将它们相加:
def one(values):
return sum(bool(x) for x in values) == 1
Run Code Online (Sandbox Code Playgroud)