Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

every element of list is True boolean

Tags:

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?

like image 861
Glassjawed Avatar asked Apr 16 '11 01:04

Glassjawed


2 Answers

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.

like image 90
Rafe Kettler Avatar answered Oct 08 '22 06:10

Rafe Kettler


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
like image 40
dting Avatar answered Oct 08 '22 06:10

dting