For loop is skipping some stuff! Python

岁酱吖の 提交于 2019-12-31 05:38:05

问题


I'm trying to run this code so that it runs a function for all elements of a list. For illustrative purposes here, basically it should print:

'----------Possible Word:', possible_word

for all items in my list. So, if I were to input ['p', 'r', 's'] it would run that print 3 times, one for each of those items. My code is below - when I run it it only runs for p and s, not r, which is really odd. Any ideas?

def check_matches(input):
print 'Input:', input
for possible_word in input:
    print '----------Possible Word:', possible_word
    valid = True
    for real_word in word_dictionary:
        possible_word_list = list(possible_word)
        real_word_list = list(real_word)
        print possible_word_list
        print real_word_list
        number_of_characters_to_check = len(possible_word_list)
        for x in range(0, number_of_characters_to_check):
            print possible_word_list[x] + real_word_list[x]
            if (possible_word_list[x] != real_word_list[x]):
                valid = False
    if (valid == False):
        input.remove(possible_word)
print all_possible
return input

回答1:


When you run input.remove(possible_word) you're changing the size of the list which you happen to be iterating over, which leads to peculiar results. In general, don't mutate anything that you're iterating over.

More concise example:

>>> lst = ['a', 'b', 'c']
>>> for el in lst:
    print el
    lst.remove(el)

a
c



回答2:


Jon Clements is right. You generally don't want to do something like this. However I'll assume you have a specific need for it.

The answer is simple. Change the line

for possible_word in input:

to this line

for possible_word in input[:]:

This will make a copy of the list for you to iterate over. That way when you remove an item it won't effect your loop.



来源:https://stackoverflow.com/questions/13635866/for-loop-is-skipping-some-stuff-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!