因为循环正在跳过一些东西!蟒蛇

时间:2012-11-29 22:23:06

标签: python loops skip

我正在尝试运行此代码,以便它为列表的所有元素运行一个函数。为了说明的目的,基本上它应该打印:

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

列表中的所有项目。因此,如果我输入['p','r','s'],它将运行该打印3次,每个项目一次。我的代码如下 - 当我运行它时它只运行p和s,而不是r,这真的很奇怪。有什么想法吗?

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

2 个答案:

答案 0 :(得分:5)

当你运行input.remove(possible_word)时,你正在改变你碰巧迭代的列表的大小,这会导致特殊的结果。一般来说,不要改变你正在迭代的任何东西。

更简洁的例子:

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

a
c

答案 1 :(得分:3)

Jon Clements是对的。你通常不想做这样的事情。但是我会假设你有特殊需要。

答案很简单。改变行

for possible_word in input:

到这一行

for possible_word in input[:]:

这将为列表的副本进行迭代。这样当你删除一个项目时它就不会影响你的循环。