在 python 中,我有一个列表应该有 一个且只有一个真值(即 bool(value) 为真
)。有没有聪明的方法来检查这个?现在,我只是遍历列表并手动检查:
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
这看起来不优雅,也不是很pythonic。有没有更聪明的方法来做到这一点?
最佳答案
不需要导入的:
def single_true(iterable):
i = iter(iterable)
return any(i) and not any(i)
或者,也许是更易读的版本:
def single_true(iterable):
iterator = iter(iterable)
# consume from "i" until first true or it's exhausted
has_true = any(iterator)
# carry on consuming until another true value / exhausted
has_another_true = any(iterator)
# True if exactly one true found
return has_true and not has_another_true
这个:
- 确保
i
具有任何真实值 - 从可迭代的那个点开始查找,以确保没有其他真实值
关于python - 如何检查列表是否只有一个真实值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16801322/