any(iterable)
如果 iterable 的任一元素为真则返回 True。 如果可迭代对象为空,返回 False。
等价于:
def any(iterable):
for element in iterable:
if element:
return True
return False
all(iterable)
如果 iterable 的所有元素为真(或可迭代对象为空),返回 True。
等价于:
def all(iterable):
for element in iterable:
if not element:
return False
return True
示例代码:
- 可迭代对象包含假元素(0, ‘’, (), [], {}, set(), None, False)
list1 = [x for x in range(0, 10, 2)]
list2 = []
for i in list1:
print(i, end='\t')
print()
print(any(list1))
print(any(list2))
print(all(list1))
print(all(list2))
运行结果:
0 2 4 6 8
True
False
False
True
- 可迭代对象不包含假元素
list1 = [x for x in range(1, 10, 2)]
list2 = []
for i in list1:
print(i, end='\t')
print()
print(any(list1))
print(any(list2))
print(all(list1))
print(all(list2))
运行结果:
1 3 5 7 9
True
False
True
True