Python's all() and any() Functions: Description, Syntax, and Examples
This article explains Python's built-in all() and any() functions, detailing their purpose, syntax, return values, and providing illustrative examples for lists, tuples, and empty iterables, highlighting behavior with truthy and falsy elements.
一、all()函数
描述 all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE, 如果是返回 True,否则返回 False。 元素除了是 0、空、FALSE 外都算 TRUE。 函数等价于: def all(iterable): for element in iterable: if not element: return False return True Python 2.5 以上版本可用。 语法 all(iterable) 参数 iterable -- 元组或列表。 返回值 如果iterable的所有元素不为0、''、False或者iterable为空, all(iterable)返回True,否则返回False; 注意:空元组、空列表返回值为True,这里要特别注意。
实例 # 列表list,元素都不为空或0 all(['a', 'b', 'c', 'd']) >>> True # 列表list,存在一个为空的元素 all(['a', 'b', '', 'd']) >>> False # 列表list,存在一个为0的元素 all([0,1,2,3]) >>> False # 元组tuple,元素都不为空或0 all(('a', 'b', 'c', 'd')) >>> True # 元组tuple,存在一个为空的元素 all(('a', 'b', '', 'd')) >>> False # 元组tuple,存在一个为0的元素 all((0,1,2,3)) >>> False all([]) >>> True all(()) >>> True
二、any()
描述 any()函数用于判断给定的可迭代参数iterable 是否全部为False,则返回False, 如果有一个为True,则返回True。 元素除了是0、空、FALSE外都算TRUE。 函数等价于: def any(iterable): for element in iterable: if element: return True return False Python2.5以上版本可用。 语法 any(iterable) 参数 iterable - - 元组或列表。 返回值 如果都为空、0、false,则返回false; 如果不都为空、0、false,则返回true。 实例 any(['a', 'b', 'c', 'd']) >>> True any(['a', 'b', '', 'd']) >>> True any([0, '', False]) >>> False any(('a', 'b', 'c', 'd')) >>> True any(('a', 'b', '', 'd')) >>> True any((0, '', False)) >>> False any([]) >>> False any(()) >>> False
说明:当给定一个不为空的可迭代对象之后:1、对于all函数,如果元素全为真则返回True,否则返回假。即只要存在为假的元素就返回假。2、对于any函数,只要存在一个为真的元素就返回True。不存在为真的元素返回假。另外,当可迭代对象为空时,all函数返回True,any函数返回False。这是因为iterable为空时遍历不执行,直接跳到 line 5 执行 return。
all函数参数为空与iterable为空时 all() Traceback (most recent call last): File " ", line 1, in all() TypeError: all() takes exactly one argument (0 given) all([]) >>> True all(()) >>> True all({}) >>> True #空list、truple、dict、str皆为True all('') >>> True
any函数参数为空与iterable为空时 any() Traceback (most recent call last): File " ", line 1, in any() TypeError: any() takes exactly one argument (0 given) any([]) >>> False any(()) >>> False any({}) >>> False any("") >>> False
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.