python中的all和any用法

有时候我们需要判断多个条件是否为True,以此做下一步的操作,那么此处的python内建函数all或者any就很有用。
此处代码均适用于python2 和python3 版本。

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> # all(obj) 只要all中的可迭代对象(多个)中出现至少一个为假,那么结果为假
>>> # all(iterable_object): iterable_object can be list,tuple or set. element can be Boolean value, number(1 or 0).
...
>>> all((1,0,1))
False
>>> all([True,False,True,True])
False
>>> all({
     "", 1, 1})
False
>>> all([" ", 1, 1])
True
>>> all([" ", 1, 0])
False
>>> all((" ")) # 此处的可迭代对象只有一个,结果为真
True
>>> all((""))  # 此处的可迭代对象只有一个,结果为真
True
>>>  # any(iterable) -> bool. Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.
...
>>> any((1,0,1))
True
>>> any([True,False,True,True])
True
>>> any({
     "", 1, 1})
True
>>> any([" ", 1, 1])
True
>>> any([" ", 1, 0])
True
>>> any((""))
False
>>> any("")
False
>>> any(" ")
True

你可能感兴趣的:(python,python)