1.all() 是什么?
all() 是 Python 内置函数,用来检查一组条件是否全部为 True。
2. 基本语法
python
all([条件1, 条件2, 条件3, ...])
如果所有条件都是 True,返回 True
如果有任何一个是 False,返回 False
3. 例子
例子1:检查数字是否都大于0
python
numbers = [5, 10, 15, 20]
python
#
conditions = []
for x in numbers:
conditions.append(x > 0) # [True, True, True, True]
result = all(conditions)
print(result) # True
# 优化为用列表推导式
result = all([x > 0 for x in numbers])
print(result) # True(因为 5>0, 10>0, 15>0, 20>0 都成立)
例子2:检查字符串是否包含多个关键词
python
text = "我喜欢吃苹果、香蕉和橙子"
# 检查是否同时包含"苹果"、"香蕉"、"橙子"
result = all([
'苹果' in text, # True
'香蕉' in text, # True
'橙子' in text # True
])
print(result) # True(三个关键词都存在)
# 反例:检查是否同时包含 苹果 香蕉 西瓜
result2 = all([
'苹果' in text, # True
'香蕉' in text, # True
'西瓜' in text # False(不存在)
])
print(result2) # False(因为有一个条件是 False)