For 循环正在跳过一些东西! Python

2023-12-30

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

'----------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

当你跑步时input.remove(possible_word)您正在更改正在迭代的列表的大小,这会导致奇怪的结果。一般来说,不要改变您正在迭代的任何内容。

更简洁的例子:

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

a
c
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

For 循环正在跳过一些东西! Python 的相关文章

随机推荐