如何解决list中的每个元素都是True boolean
| 我知道all(map(compare,new_subjects.values()))==True
会告诉我列表中的每个元素是否为True。但是,如何判断除其中一个元素之外的每个元素是否都是True?
解决方法
values = map(compare,new_subjects.values())
len([x for x in values if x]) == len(values) - 1
基本上,您可以过滤列表中的真值,然后将列表的长度与原始列表进行比较,以查看列表是否少了一个。
,如果您的意思是实际上是True
且未计算为True,那么您可以算一下吗?
>>> L1 = [True]*5
>>> L1
[True,True,True]
>>> L2 = [True]*5 + [False]*2
>>> L2
[True,False,False]
>>> L1.count(False)
0
>>> L2.count(False)
2
>>>
仅检查单个False:
>>> def there_can_be_only_one(L):
... return L.count(False) == 1
...
>>> there_can_be_only_one(L1)
False
>>> there_can_be_only_one(L2)
False
>>> L3 = [ True,False ]
>>> there_can_be_only_one(L3)
True
>>>
编辑:这实际上更好地回答了您的问题:
>>> def there_must_be_only_one(L):
... return L.count(True) == len(L)-1
...
>>> there_must_be_only_one(L3)
True
>>> there_must_be_only_one(L2)
False
>>> there_must_be_only_one(L1)
False
,计算有多少不是True:
values = (compare(val) for val in new_subjects.itervalues())
if sum(1 for x in values if not x) == 1: # just one
...
,假设compare函数返回一个布尔值,并且知道True / False在整数上下文中为1/0,则可以执行以下操作:
values = new_subjects.values()
sum(compare(v) for v in values) == len(values) -1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。