Python中的any函数
any字面意思任何一个,any函数用于判定给定的可迭代参数中的元素是否全部为False,如果其中的任何一个为True,则返回 True,否则,返回False。
元素除了是 0、空、FALSE 外都算 TRUE。
>>> any(['a', 'b', 'c', 'd']) # 列表list,元素都不为空或0
True
>>> any(['a', 'b', '', 'd']) # 列表list,存在一个为空的元素
True
>>> any([0, '', False]) # 列表list,元素全为0,'',false
False
>>> any(('a', 'b', 'c', 'd')) # 元组tuple,元素都不为空或0
True
>>> any(('a', 'b', '', 'd')) # 元组tuple,存在一个为空的元素
True
>>> any((0, '', False)) # 元组tuple,元素全为0,'',false
False
>>> any([]) # 空列表
False
>>> any(()) # 空元组
False
除了上面对基本可迭代对象的直接判定,还可以对较复杂的可迭代对象通过增加判定条件进行判定。
>>> msgs = [{"type":"AA","name":"msg1"},{"type":"AA","name":"msg2"},{"type":"BB","name":"msg3"}]
>>> if any(msg['type'] == "BB" for msg in msgs):
print("Not all AA")
else:
print("All AA")
Not all AA
Python中的all函数
all 字面意思为所有的,all函数用于判断给定的可迭代参数中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。
>>> all(['a', 'b', 'c', 'd']) # 列表list,元素都不为空或0
True
>>> all(['a', 'b', '', 'd']) # 列表list,存在一个为空的元素
False
>>> all([0, 1,2, 3]) # 列表list,存在一个为0的元素
False
>>> all(('a', 'b', 'c', 'd')) # 元组tuple,元素都不为空或0
True
>>> all(('a', 'b', '', 'd')) # 元组tuple,存在一个为空的元素
False
>>> all((0, 1, 2, 3)) # 元组tuple,存在一个为0的元素
False
>>> all([]) # 空列表
True
>>> all(()) # 空元组
True
同样的,还可以对复杂的可迭代参数,通过增加判定条件,对其进行判定。
>>> msgs = [{"type":"AA","name":"msg1"},{"type":"AA","name":"msg2"},{"type":"BB","name":"msg3"}]
>>> if all(msg['type'] == "AA" for msg in msgs):
print("all AA")
else:
print("Not all AA")
Not all AA