python中的函数any和all

时间:2025-02-11 09:40:11

python中又很多好玩的函数,下面说一下内建函数any()和all():


any(...)

    any(iterable) -> bool

    

    Return True if bool(x) is True for any x in the iterable.

    If the iterable is empty, return False.

以上是python doc中得说明,意思就是当传入空可迭代对象时返回False,当可迭代对象中有任意一个不为False,则返回True


all(...)

    all(iterable) -> bool

    

    Return True if bool(x) is True for all values x in the iterable.

    If the iterable is empty, return True.

以上是python doc中得说明,意思就是当传入空可迭代对象时返回True,当可迭代对象中有任意一个不为True,则返回False


示例:

>>> any('123')

True

>>> any([0, 1])

True

>>> any([0, ''])

False

>>> all('123')

True

>>> all([0, 1])

False

>>> all([1, 2])

True