Python all函数 判断是否同时满足多个条件

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)
相关推荐
inksci2 小时前
Python 中使用 SQL 连接池
服务器·数据库·python
子午2 小时前
【2026原创】中草药识别系统实现~Python+深度学习+模型训练+人工智能
人工智能·python·深度学习
shejizuopin2 小时前
基于JavaSSM+MySQL的实验室考勤管理系统设计与实现
java·mysql·vue·毕业设计·论文·springboot·实验室考勤管理系统设计与实现
洛克大航海2 小时前
Python 在系统 Windows 和 Ubuntu 中创建虚拟环境
windows·python·ubuntu·虚拟环境
ZEERO~2 小时前
@dataclass的作用
开发语言·windows·python
optimistic_chen2 小时前
【Docker入门】容器技术
linux·运维·服务器·docker·容器
Lueeee.2 小时前
2.智梯云枢・全维管控广告系统——解决串口卡顿 + 优化稳定性
linux·运维·服务器
J***51682 小时前
SpringSecurity的配置
java
June`2 小时前
IO模型全解析:从阻塞到异步(高并发的reactor模型)
linux·服务器·网络·c++