【Python】内置函数all()
语法:
1 |
all(iterable) |
描述:如果迭代器的所有元素均为真(或迭代器为空),则返回True。 all()相当于效果:
1 2 3 4 5 |
def all(iterable): for element in iterable: if not element: return False return True |
问:所有元素均为真,则返回True,哪些元素自己本身为False
从以下结果我们可以看到,0和‘’均为False,也就是说,如果列表、元组中包含0或‘’,则返回False
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
>>> not 0 True >>> not 1 False >>> not 2 False >>> >>> not 'a' False >>> not 'b' False >>> >>> not '' True >>> |
例1,元组
1 2 3 4 5 6 7 8 9 |
>>> all(('a', 'b', 'c', 'd')) True >>> all(('a', 'b', '', 'd')) False >>> all((1, 2, 3)) True >>> all((0, 1, 2, 3)) False >>> |
例2:列表
1 2 3 4 5 6 7 8 9 |
>>> all(['a', 'b', 'c', 'd']) True >>> all(['a', 'b', '', 'd']) False >>> all([1, 2, 3]) True >>> all([0, 1, 2, 3]) False >>> |
例3:迭代器为空,返回True
1 2 3 4 5 |
>>> all([]) True >>> all(()) True >>> |