Check if the characters in a string are contained in any of the word of a list

I need to find a way to check if given characters are contained in any of the words of a very long list.

I suppose you could do it by checking every indexes of the words in the list, a bit like so:

for i in list:
    if i[0] == 'a' or 'b':
       found_words.append(i)
    if i[1] == 'a' or 'b':
       found_words.append(i)

But this is not a very stylish and not a very efficient way of doing it.

Thanks for your help

Upvotes: 0

Views: 111

Answers (3)

user2390182
user2390182

Reputation: 73460

You could do the following:

check = set('ab').intersection  # the letters to check against
lst = [...]  # the words, do not shadow the built-in 'list'

found_words = [w for w in lst if check(w)]

or shorter:

found_words = list(filter(check, lst))

Upvotes: 1

Corsaka
Corsaka

Reputation: 422

If you want to match characters in lists, you can use regular expressions.

import re

for i in lst:
    re.match(str,i) #returns "true", use in conditionals

Replace "str" with the characters you want to check for, e.g "[abcde]", which matches "a","b","c","d", or "e" in any word, or "[abcde][pqrst]" which matches any combination of "ap", "at", "eq", etc. Do so with a variable so you can change it far more easily.

Upvotes: 1

Taha
Taha

Reputation: 675

A more understandable way of doing this is the following:

character='e'

for i in list:
    if character in i:
       found_words.append(i)

Upvotes: 1

Related Questions