So, the general format for this is something like this:
test = [True, True, False]
if len([x for x in test if x]) == 1:
# Do something
Of course, the above is just testing if x
is boolean True
, but you could put any kind of comparison there.
You might say, but isn't that inefficient? Not really, if you really want exactly N items - you'd have to check them all anyways to see if there is another True
lurking in there.
For the case where it's 'N or more' items, you can kind of (ab)use generators to do this:
from itertools import islice
result = True
g = (x for x in test if x)
if len(list(islice(g, 2))) == 2:
# do something
This is a bit of a shortcut, since it will stop as soon as it sees the number of items and not walk farther through the generator. If you wanted to use this form for an exact count, it has a small advantage over the list form:
if len(list(islice(g, 2))) == 2 and not any(g):
# do something
Why does this have a small advantage? In the passing case, we still have to look through every other item to make sure there are exactly 2 Trues
in the list. But in the failing case, as soon as we see another True
, the any
will shortcut and you won't walk through the rest of the list.