Home > Net >  How to filter a string list containing specific characters in python
How to filter a string list containing specific characters in python

Time:02-07

I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:

letters = ['R', 'E', 'T', 'O', 'P', 'A']

letters = ['R', 'E', 'T', 'O', 'P', 'A']

final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]

Does anybody have an idea of how to do that?

Thank you in advance!

CodePudding user response:

You can filter your list using python filter() method.

CodePudding user response:

You are almost there, you just need to tweak your all condition a bit.

all(word for letter in letters if letter in word) -> this would return True as long as any word is True which would always be the case.

What we want to check is that "all letters in the word are part of letters", letter in letters in the following code would return True/False if a letter is in letters. So with all, it would only return True if all letter in letters checks return True.

letters = ['R', 'E', 'T', 'O', 'P', 'A']
dictionary = ['REPORT', 'INVALID', 'ROPE']
final_list = [word for word in dictionary if all(letter in letters for letter in word)]
print(final_list)

outputs -

['REPORT', 'ROPE']

CodePudding user response:

You can use the filter() method in python

letters = ['R', 'E', 'T', 'O', 'P', 'A']
my_lis = ['jake','jill','tim','vim'] 

def foo(x):
  for words in x:
    for letter in words:
        print(letter)
        if letter in letters:
            return True
        else:
            return False

final = filter(foo,my_lis)

for x in final:
  print(x)
  •  Tags:  
  • Related