社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在Python中缩写这个条件?[重复]

4daJKong • 3 年前 • 1121 次点击  

我有这样的情况:

str1 = "cat, dog, rat"
print( ("cat" not in str1) and ("dog" not in str1) and ("rat" not in str1)) #1
print(any(x not in str1 for x in ("cat","dog","rat"))) #2

问题是,如果我添加任何其他语句,那么#1条件太长,所以我将其转换为#2,但是#2返回相反的结果,那么如何简单地用Python编写#1呢?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132483
 
1121 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Tim Biegeleisen
Reply   •   1 楼
Tim Biegeleisen    3 年前

你可以用 re.search 这里有一个regex替换:

str1 = "cat, dog, rat"
regex = r'\b(?:' + r'|'.join(re.split(r',\s*', str1)) + r')\b'
if not re.search(regex, str1):
    print("MATCH")
else:
    print("NO MATCH")
Antoine Delia
Reply   •   2 楼
Antoine Delia    3 年前

正如@Sayse提到的,你应该使用 all 而不是 any

words_to_check = ["cat", "dog", "rat"]

str1 = "cat, dog, rat"

if all(word in str1 for word in words_to_check):
    print("All words are present")
else:
    print("Not all words are present")

产出:

All words are present