paul_on_pc
paul_on_pc

Reputation: 139

Test if any item in a list is part of another list of strings

Imagine I have a list of key-words:

terms = ["dog","cat","fish"]

And I also have another list that contain longer strings of texts:

texts = ["I like my dog", "Hello world", "Random text"]

I now want that I have a code that basically goes through the list texts and checks if it contains any of the items in the list terms and it should return a list that contains if this item in texts had a match.

This is what the code should produce:

result = ["match","no match","no match"]

Upvotes: 0

Views: 85

Answers (1)

Red
Red

Reputation: 27577

Here is how you can use zip() and a list comprehension:

terms = ["dog","cat","fish"]

texts = ["I like my dog", "Hello world", "Random text"]

results = ["match" if a in b else "no match" for a,b in zip(terms,texts)]

print(results)

Output:

['match', 'no match', 'no match']

UPDATE: Turns out the zipping wasn't what the OP wanted.

terms = ["dog","cat","fish"]

texts = ["I like my dog", "Hello world", "Random text"]

results = ["match" if any(b in a for b in terms) else "no match" for a in texts]

print(results)

Output:

['match', 'no match', 'no match']

Upvotes: 1

Related Questions