'Filtering words containing certain characters from a list
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"]
Solution 1:[1]
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)
Solution 2:[2]
Using set objects makes this pretty straight forward (and is the only solution so far which doesn't require iterating over the letters of each word using Python -- set.intersection() defers to the underlying C code to iterate over each letter):
words = ["clyde", "tool", "ball", "window"]
letters = {"c", "t"} # a set object
filtered_words = [word for word in words if not letters.intersection(word)]
Solution 3:[3]
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
Solution 4:[4]
Simple to understand code example
words_list = ["clyde","tool","ball","actor","window"]
letters = ["c","t"]
final_list=[]
# 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:
break
else:
final_list.append(word)
print(final_list)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrokenBenchmark |
| Solution 2 | |
| Solution 3 | maya |
| Solution 4 |
