简体   繁体   中英

List Comprehension for items in list

list comprehension to check for presence of any of the items.

I have some text and would like to check on some keywords. It should return me the sentence if it contains any of the keywords.

An example:


     text = [t for t in string.split('. ') 

     if 'drink' in t or 'eat' in t 

     or 'sleep' in t]

This works. However, I am thinking if there is a better way, as the list of keywords may grow.

I tried putting the keywords in a list but it would not work in this list comprehension. OR using if any

     pattern = ['drink', 'eat', 'sleep']

     [t for t in string.split('. ') if any (l in pattern for l in t)]

You were almost there:

pattern = ['drink', 'eat', 'sleep']
[t for t in string.split('. ') if any(word in t for word in pattern)]

The key is to check for each word in pattern if that work is inside the sentence:

any(word in t for word in pattern)

Your use of any is backwards. This is what you want:

[t for t in string.split('. ') if any(l in t for l in pattern)]

An alternative approach is using a regex:

import re

regex = '|'.join(pattern)

[t for t in string.split('. ') if regex.search(t)]

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