简体   繁体   中英

How to filter a string list containing specific characters in python

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!

You can use this way to solve the problem.

letters = ['R', 'E', 'T', 'O', 'P', 'A']
words_list = ["TOP", "CUT", "REPORT", "GOOD"]

final_list = [word for word in words_list if set(word).issubset(set(letters))]
print(final_list)

In this code, we are checking each word in the words_list whether that word is made of letters in the letters_list . To do that we use the issubset method.

set(word).issubset(set(letters)) this part of code is return a boolean value. We include that word to final_list if and only if that boolean value is True .

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']

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM