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

Sam*_*her 0 python loops skip

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

'----------Possible Word:', possible_word
Run Code Online (Sandbox Code Playgroud)

对于我列表中的所有项目.因此,如果我输入['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
Run Code Online (Sandbox Code Playgroud)

Jon*_*nts 5

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

更简洁的例子:

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

a
c
Run Code Online (Sandbox Code Playgroud)

  • 不要从列表中删除无效项,而是尝试创建一个新列表并添加**有效的元素.那会给你想要的结果. (3认同)