AndreMSilv
AndreMSilv

Reputation: 1

Selecting data in a list of strings

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.

Upvotes: 0

Views: 34

Answers (2)

mozway
mozway

Reputation: 262484

I would use set operations.

You want to check is the set of your words is a subset of the words of the strings, use issubset:

W = {word1, word2}

out = [s for s in list_words if W.issubset(s.split())]

Output:

['cow light gate white']

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61930

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)

Upvotes: 1

Related Questions