For循环正在跳过一些内容! Python [英] For loop is skipping some stuff! Python

查看:79
本文介绍了For循环正在跳过一些内容! Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

运行input.remove(possible_word)时,您正在更改恰好要遍历的列表的大小,这将导致特殊的结果.通常,请勿更改要迭代的任何内容.

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.

更简洁的示例:

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

a
c

这篇关于For循环正在跳过一些内容! Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆