在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
这看起来不雅,也不是很Python。有比这更聪明的方法吗?
最冗长的解决方案并不总是最不合理的解决方案。因此,我只添加了一个小修改(为了保存一些多余的布尔计算):
下面是一些比较的时间安排:
我的输出:
可以看到,OP解决方案明显优于这里发布的大多数其他解决方案。正如所料,最好的是那些短路行为,特别是由乔恩克莱门茨张贴的解决方案。至少对于长列表中两个早期
True
值的情况。这里完全没有
True
值:我没有检查统计意义,但有趣的是,这次F.J.提出的方法,特别是Jon Clements提出的方法,似乎再次显示出明显的优越性。
不需要进口的:
或者,也许是更可读的版本:
这:
i
具有任何真实值这取决于您是在寻找值
True
,还是在寻找逻辑上计算为True
的其他值(如11
或"hello"
)。如果前者:如果是后者:
因为这将在一次迭代中完成计数和转换,而无需构建新的列表。
相关问题 更多 >
编程相关推荐