Reputation: 11
I have a list in python which contains a lot of different characters, for example space, |, >, numbers, and small letters, but I only want to keep some capital letter (A,B,C,D). If I try this, it doesen't work, I almost get the desired list, but not only A,B,C,D remain.
with open("text.mfa") as f:
content = f.read()
mylist = list(content)
letters = ['A','B','C','D']
i = 0
while i < (len(mylist)-1)
if mylist[i] != letters[0] or letters[1] or letters[2] or letters[3]
mylist.remove(mylist[i])
i+=1
Upvotes: 0
Views: 2636
Reputation: 33724
You can use a for loop instead of a while loop since for loop iterates over a set number of values. To check if the word is in letters you can do this:
with open("text.mfa") as f:
mylist = list(f.read())
mynewlist = []
letters = ['A','B','C','D']
for word in mylist:
if word not in letters: #if word is not in letters
mynewlist.append(word) #adds the word to a new list
Upvotes: 0
Reputation: 114330
A more Pythonic way would probably be to use a list comprehension and the in
operator:
mylist = [x for x in content if x in letters]
Upvotes: 2
Reputation: 474
Try using filter.
myfilteredlist = list(filter(lambda s: s in letters, mylist))
Upvotes: 2
Reputation: 177
Use in
instead of or
(this check if the element is in the list).
if not mylist[i] in letters:
mylist.remove(mylist[i])
Upvotes: 0
Reputation: 4451
Let's take a look at your if statement:
if mylist[i] != letters[0] or letters[1] or letters[2] or letters[3]
If put in brackets python processes this as:
if (mylist[i] != letters[0]) or (letters[1]) or (letters[2]) or (letters[3]):
Every character evaluates to True, to this means that because letters[1] etc. evaluate to true you always evaluate your whole expression to True.
Upvotes: 0