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)
相关推荐
二哈赛车手7 小时前
新人笔记---ApiFox的一些常见使用出错
java·笔记·spring
wj3055853787 小时前
课程 9:模型测试记录与 Prompt 策略
linux·人工智能·python·comfyui
栗子~~8 小时前
JAVA - 二层缓存设计(本地缓冲+redis缓冲+广播所有本地缓冲失效) demo
java·redis·缓存
星寂樱易李8 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
YDS8298 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— RAG知识库的搭建和接口实现
java·ai·springboot·agent·rag·deepseek
wangqiaowq8 小时前
windows下nginx的安装
linux·服务器·前端
qingfeng154158 小时前
企业微信机器人开发:如何实现自动化与智能运营?
人工智能·python·机器人·自动化·企业微信
未若君雅裁9 小时前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis
cen__y10 小时前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git