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)
相关推荐
懂点Tech6 小时前
ctfshow misc28:GIF 高度修改解题与脚本实现
开发语言·windows·python
广州灵眸科技有限公司6 小时前
4G 模组开机自连 systemd 服务方案:基于灵眸科技EAI1106--Core-T
运维·服务器·科技
comedate6 小时前
SMLib 的 Examples 导读:PyAPI / SM_API / SMLib 三组示例怎么读
python·cad·smlib·examples·sm_api
云和数据.ChenGuang6 小时前
Python 重写(Override)深度解析:从 MRO 到 super() 的完整机制
java·开发语言·人工智能·python·langchain·1024程序员节
摇滚侠7 小时前
《On Java 中文版 基础卷》阅读笔记 实现隐藏 12
java·数据库·笔记
川石课堂软件测试7 小时前
学习软件测试需掌握的一些知识
数据库·python·sql·功能测试·网络协议·mysql·http
万化冥合8 小时前
PyBox屏幕键盘如何辅助演示键盘操作?
python·计算机外设
qq_401700418 小时前
Linux设备树详解
linux·运维·服务器
车软学堂8 小时前
从测试转开发,到底要补什么
网络·人工智能·python·功能测试·单片机·车载系统·自动化
天空依然蔚蓝8 小时前
分享一个自动检测网站在线状态的python程序
python·运维开发·1024程序员节