Python return 字符串包含的列表项

Python return which list items string contains

我有一个单词列表和一个字符串,如下所示:

wordlist = ['fox', 'over', 'lazy']
paragraph = 'A quick brown fox jumps over the lazy fox.'

我想知道列表中的哪些单词出现在字符串中以及 return 它们。有没有一些相对聪明的方法来做到这一点?

例如,any(word in paragraph for word in wordlist) 仅 returns TrueFalse,而不是实际找到的单词。

在列表理解中使用你的测试:

words_in_paragraph = [word for word in wordlist if word in paragraph]

这将 any() 生成器的测试移到了最后。

演示:

>>> wordlist = ['fox', 'over', 'lazy']
>>> paragraph = 'A quick brown fox jumps over the lazy fox.'
>>> [word for word in wordlist if word in paragraph]
['fox', 'over', 'lazy']
>>> another_wordlist = ['over', 'foo', 'quick']
>>> [word for word in another_wordlist if word in paragraph]
['over', 'quick']

请注意,就像您的 any() 测试一样,这当然也适用于 部分 单词匹配:

>>> partial_words = ['jump', 'own']
>>> [word for word in partial_words if word in paragraph]
['jump', 'own']

您可以使用过滤器

included_words = filter(lambda word: word in paragraph, wordlist)

虽然在 python3 中,这会生成一个迭代器,因此如果您想要一个列表,请使用列表理解方法(或者如果您愿意,您可以只在过滤结果上调用列表),否则迭代器就可以了.

included_words = list(filter(lambda word: word in paragraph, wordlist))

included_words = [word for word in wordlist if word in paragraph]