简体   繁体   中英

Implementing .all() for a list of booleans?

Numpy has a great method .all() for arrays of booleans, that tests if all the values are true. I'd like to do the same without adding numpy to my project. Is there something similar in the standard libary? Otherwise, how would you implement it?

I can of course think of the obvious way to do it:

def all_true(list_of_booleans):
    for v in list_of_booleans:
        if not v:
            return False
    return True

Is there a more elegant way, perhaps a one-liner?

There is; it is called all() , surprisingly. It is implemented exactly as you describe, albeit in C. Quoting the docs:

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

 def all(iterable): for element in iterable: if not element: return False return True 

New in version 2.5.

This is not limited to just booleans. Note that this takes an iterable ; passing in a generator expression means only enough of the generator expression is going to be evaluated to test the hypothesis:

>>> from itertools import count
>>> c = count()
>>> all(i < 10 for i in c)
False
>>> next(c)
11

There is an equivalent any() function as well.

有一个类似的函数,称为all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM