Home > OS >  Selecting data in a list of strings
Selecting data in a list of strings

Time:01-03

I have a list of strings, and I would like to do a filter, using 2 words combined. As example:

list_words = ['test cat dog tree',
       'bird time headphone square',
        'cow light gate white', 
        'soccer baseball box volley',
        'clock universe god peace']

word1 = 'gate'
word2 = 'white'

In this example, I would like to return the list item on position [2]: 'cow light gate white', once the user has added two words that is combined with the entire phrase. Seems easy, but I am really stuck on it.

CodePudding user response:

One approach, that works for any number of words inputed by the user, is to use all:

res = [sentence for sentence in list_words if all(w in sentence for w in [word1, word2])]
print(res)

Output

['cow light gate white']

The above list comprehension is equivalent to the below for-loop:

test_words = [word1, word2]
res = []
for sentence in list_words:
    if all(w in sentence for w in test_words):
        res.append(sentence)
        
print(res)

CodePudding user response:

You can try this:

list_words = ['test cat dog tree',
       'bird time headphone square',
        'cow light gate white', 
        'soccer baseball box volley',
        'clock universe god peace']

word1 = 'gate'
word2 = 'white'
filtered_list = [s for s in list_words if word1 in s and word2 in s]
filtered_list
  • Related