No items removed from the list
I am using Python 3.5 and my code is
words = open("wordlist.txt").readlines()
words = [k[:-2] for k in words]
noletters = ["b", "d", "f", "g", "h", "i", "j", "k", "l", "p", "q", "t", "y"]
for n in words:
for i in n:
if i in noletters:
words.remove(n)
break
words.sort()
words.sort(key = len)
print(words)
Here wordlist.txt
is a really, really, really long list of words . First, I remove unnecessary characters from each item in the list, and then I end up with a list where each item is a word - something like 'hello'
or yugoslavia
. It still works.
Then I create a list of letters that I do not want in any of the words I get from the program. Then, for each item in the list, I check every letter in the word, and if the letter is in the list, I remove the word from the list and exit the inner loop that checks the letters (this prevents the system from trying to remove what has already been removed). Then I sort the list alphabetically and by word length and the list is printed.
Problems:
- Nothing is removed from the list by loops and I have no idea why. Of course it hits the loops - I've added a few print statements (after the print line
words.remove(n)
when something was deleted, and also after the linebreak
to see when it went to a new word). - The operator that sorts by string length also adds a bunch of things that were never in the word list - for example,
'o'
it wasn't in the list, but it was added along with several empty strings (''
), etc. - it looked like every possible combination of every letter of the alphabet.
source to share
From the document for the operator .
If you need to change the sequence that you are repeating while inside the loop (for example, to duplicate selected items), it is recommended that you make a copy first . Iterating over a sequence does not implicitly make a copy.
If I misunderstand your meaning, perhaps you can try to make a shallow copy:
for n in words[:]:
for i in n:
if i in noletters:
words.remove(n)
break
Or maybe you can use this list comprehension:
words=[n for n in words if not any([i in noletters for i in n])]
Hope it helps.
source to share