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)
相关推荐
2601_962297252 分钟前
Python、Pytest、Allure、Selenium和Jenkins实现自动化测试集成实例
python·selenium·jenkins·pytest·allure
tedcloud1234 分钟前
OpenLogi 怎么搭建?用 Rust 打造一个轻量的 Logitech 外设管理工具
linux·运维·服务器·开发语言·后端·rust·开源
霸道流氓气质16 分钟前
Spring AI 技术细节:VectorStore 多库统一抽象
java·人工智能·spring
今天AI了吗17 分钟前
Codex 配置自定义 AI API 完整指南:从零到一接入你的专属模型
java·人工智能·python·数据分析·embedding
阿童木写作23 分钟前
跨境电商批量图片翻译与视频字幕翻译工具推荐
python·音视频
leihefeng31 分钟前
手写数字识别:KNN vs 逻辑回归实战
python·算法·机器学习·逻辑回归·scikit-learn
学长毕业设计37 分钟前
基于SpringBoot的健康食谱管理系统的设计与实现(源码+文档+讲解视频)
java·spring boot·后端
珍珠先生38 分钟前
P10 · 缺 MySQL 驱动 jar:ClassNotFoundException: com.mysql.cj.jdbc.Driver
java
SunnyDays101143 分钟前
如何使用 Python 从 Word 文档中提取图片
python·word
2601_962097361 小时前
Pathway 实时RAG新方案:抛弃Spark、Flink,生产级数据管道
python·流处理·大数据集群·实时rag·pathway