擅长:python、mysql、java
<p>您可以使用<a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow noreferrer">^{<cd1>}</a>和<a href="https://docs.python.org/3/library/functions.html#filter" rel="nofollow noreferrer">^{<cd2>}</a>的组合来实现这一点。我们使用<code>any</code>忽略在<code>no</code>中出现单词的字符串。否则,我们使用<code>filter</code>查找匹配:</p>
<pre><code>string1 = ['I love apple', 'Banana is yellow', "I have no school today", "Baking pies at home", "I bought 3 melons today"]
no = ['strawberry', 'apple', 'melon', 'Banana', "cherry"]
school = ['school', 'class']
home = ['dinner', 'Baking', 'home']
for s in string1:
if not any(x in s for x in no):
first_match = list(filter(lambda x: x in s, school + home))[0]
print(s)
print(first_match)
</code></pre>
<p><strong>输出</strong></p>
<pre><code>I have no school today
school
Baking pies at home
Baking
</code></pre>