开发者

every element of list is True boolean

I know that

all(map(compare,new_subjects.values()))==True

would tell me if every element of the list is True. However, how do 开发者_开发技巧I tell whether every element except for one of them is True?


values = map(compare, new_subjects.values())
len([x for x in values if x]) == len(values) - 1

Basically, you filter the list for true values and compare the length of that list to the original to see if it's one less.


If you mean is actually True and not evaluates to True, you can just count them?

>>> L1 = [True]*5
>>> L1
[True, True, True, True, True]
>>> L2 = [True]*5 + [False]*2
>>> L2
[True, True, True, True, True, False, False]
>>> L1.count(False)
0
>>> L2.count(False)
2
>>> 

checking for only a single 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, True, False ]
>>> there_can_be_only_one(L3)
True
>>> 

edit: This actually answer your question better:

>>> 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


Count how many are not True:

values = (compare(val) for val in new_subjects.itervalues())
if sum(1 for x in values if not x) == 1: # just one
    ...


Assuming the compare function returns a boolean vaue, and knowing that True/False become 1/0 in an integer context you can do:

values = new_subjects.values()
sum(compare(v) for v in values) == len(values) -1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜