I am trying to run a simple python script that removes certain words containing certain letters originally part of a string, correctly separated into a list of words. I re-checked the code multiple times, yet the results are erroneous. What needs to be changed because I believe the code is correct. Please help.
s = """aline amine
avine azine
brine chine
cline coine
crine daine
dwine exine
ezine faine
feine foine
gwine imine
koine laine
Maine opine
ovine peine
quine raine
rhine saine
seine shine
spine swine
thine trine
tsine twine
Udine urine
whine"""
words = list(s.split())
for i in words:
if "s" in i:
words.remove(i)
elif "a" in i:
words.remove(i)
elif "d" in i:
words.remove(i)
elif "w" in i:
words.remove(i)
elif "u" in i:
words.remove(i)
print(words)
CodePudding user response:
In general, it's a bad idea to remove elements from a list as you're iterating over it, as the memory is shifting as you're trying to access it.
Instead, create a new list (using a list comprehension), only retaining the words which do not contain any of the forbidden letters (checking for whether a word contains a letter is done using in
, and we generalize it to multiple letters using map()
).
words = s.split()
result = [word for word in words if not any(map(lambda x: x in word, "adsuw"))]
CodePudding user response:
You can also use the filter
function which filters a list given a criterion.
def criterion(str_):
# Returns True if str_ has none of the characters in list_
# Returns False otherwise
return all(c not in str_ for c in list_)
words = s.split()
list_ = ['s', 'a', 'd', 'w', 'u']
# also works: list_ = 'sadwu'
result = list(filter(criterion, words))
or, in one line:
result = list(filter(lambda str_: all(c not in str_ for c in 'sadwu'), s.split()))
CodePudding user response:
This would do the job, too:
words = list(s.split())
ex = ["s", "a", "d", "w", "u"]
words = [i for i in words if all(e not in i for e in ex)]