Py学习  »  Python

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

4daJKong • 3 年前 • 1232 次点击  

我有这样的情况:

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
 
1232 次点击  
文章 [ 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