Home > Mobile >  Filtering words containing certain characters from a list
Filtering words containing certain characters from a list

Time:02-23

I have a list of words and a list of letters:

list = ["clyde","tool","ball","window"]
letters = ["c","t"]

I want to filter the first list by removing the word if it has any letters from the second list.

list = ["ball","window"]

CodePudding user response:

You can use filter() and all() to only retain words that do not have any letters that appear in letters (as an aside, you shouldn't use list as a variable name, as it shadows the list builtin):

data = ["clyde","tool","ball","window"]
letters = ["c","t"]

result = list(filter(lambda x: all(c not in x for c in letters), data))

# Prints ['ball', 'window']
print(result)

CodePudding user response:

Using set objects makes this pretty straight forward:

words = ["clyde", "tool", "ball", "window"]
letters = {"c", "t"}  # a set object

filtered_words = [word for word in words if not letters.intersection(word)]

CodePudding user response:

You can also do it like this :-

list = ["clyde","tool","ball","window"] 
letters = ["c","t"] 
out = [i for i in list if not i[0] in letters]
print(out)

Output:

['ball', 'window']

CodePudding user response:

Simple to understand code example

words_list = ["clyde","tool","ball","window"]
letters = ["c","t"]
elements_to_remove=[]
# loop for each word in main list
for word in words_list:
    #check for each letter if present in restricted letters
    for letter in word:
        if letter in letters:
            #if present store word to remove
            elements_to_remove.append(word)
            break

#remove prohibited words from the list      
for element in elements_to_remove:
    words_list.remove(element)
print(words_list)


CodePudding user response:

This problem can be solved using List Comprehensions,like this:

lst = ["clyde","tool","ball","window"]
letters = ["c","t"]

res = [data for data in lst if all(item not in data for item in letters)]
print(res)

Please note that it is better not to have variables with the same name as keywords in python,so I changed the list to lst

  • Related