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)
相关推荐
测试员周周9 小时前
【AI测试智能体-面试】AI测试面试60题(附回答思路)
人工智能·python·功能测试·测试工具·单元测试·自动化·测试用例
SamDeepThinking9 小时前
我们当年是如何真实落地BFF的?
java·后端·架构
码语智行9 小时前
Shapefile获取空间数据和中心点坐标
java·arcgis
caoyc9 小时前
RAG 赛道全景扫描:ragflow 一骑绝尘、微软谷歌跟进乏力、下半场属于 Agent
java
屋外雨大,惊蛰出没9 小时前
深入浅出Spring Boot
java·spring boot·ioc·aop
用户8356290780519 小时前
使用 Python 操作 Word 评论和回复
后端·python
Zella折耳根10 小时前
复习篇-继承和接口
java·开发语言·python
诗词在线10 小时前
求推荐飞花令
大数据·人工智能·python
程序员二叉10 小时前
【JVM】OOM详解+JVM参数+FullGC排查+CPU飙高+死锁+内存泄漏+命令大全
java·开发语言·jvm·面试