简体   繁体   中英

Python return which list items string contains

I have a list of words and a string like so:

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

I want to know which words in the list occur in the string and return them. Is there some relatively clever way to do this?

For example, any(word in paragraph for word in wordlist) only returns True or False , but not the actual words that were found.

Use your test in a list comprehension:

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

This moved the test for the any() generator to the end.

Demo:

>>> 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']

Note that, just like your any() test, this'll work for partial word matches too, of course:

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

You can use filter

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

Although in python3, this would generate an iterator, so if you want a list use list comprehension approach (or you can just call list on filter result if you prefer), otherwise iterator would do just fine.

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

OR

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM