freeCodeCamp/guide/chinese/python/all-iterable/index.md

1.6 KiB
Raw Blame History

title localeTitle
Python All Iterable Python所有Iterable

all()是Python 3中的内置函数以及2.5版以来的Python 2用于检查iterable的所有项是否为True 。它需要一个参数, iterable

论据

迭代

iterable参数是要检查其条目的集合。它可以是list str dict tuple等。

回报价值

返回值是一个布尔值。当且仅当iterable 所有条目都是真实的时 ,它返回True 。该函数基本上对所有元素执行布尔AND运算。

如果它们中的一个不是真的,则返回False

all()操作等效于(不是内部实现完全像这样)

def all(iterable): 
    for element in iterable: 
        if not element: 
            return False 
    return True 

代码示例

print(all([])) #=> True  # Because an empty iterable has no non-truthy elements 
 print(all([6, 7])) #=> True 
 print(all([6, 7, None])) #=> False  # Because it has None 
 print(all([0, 6, 7])) #=> False  # Because it has zero 
 print(all([9, 8, [1, 2]])) #=> True 
 print(all([9, 8, []])) #=> False  # Because it has [] 
 print(all([9, 8, [1, 2, []]])) #=> True 
 print(all([9, 8, {}])) #=> False  # Because it has {} 
 print(all([9, 8, {'engine': 'Gcloud'}])) #=> True 

:rocket: 运行代码

官方文件