2012-11-29 52 views
0

我想运行此代码,以便它运行列表中的所有元素的函数。出于说明的目的,基本上它应该打印:For循环跳过一些东西! Python

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

在这个.py和顶部的变量启动还有其他函数,但我不想发布一个巨大的丑块,并认为这是所有相关的。如果你认为我应该发表其余的,请说。 –

+0

所以我们将假设word_dictionary是全局列表权并且之前定义了? – Hamoudaq

回答

5

当您运行input.remove(possible_word)你改变你的出现列表的大小进行迭代,从而导致奇特的效果。一般来说,不要改变任何你正在迭代的东西。

更简洁例如:

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

a 
c 
+0

好的 - 有道理。对不起,我错过了。 –

+3

不要从列表中删除无效项目,请尝试制作新列表并添加* *有效的元素。这应该给你你想要的结果。 –

3

乔恩·克莱门茨是正确的。你通常不想做这样的事情。不过,我会假设你有特定的需求。

答案很简单。行

for possible_word in input: 

更改此行

for possible_word in input[:]: 

这将使列表的副本供你遍历。这种方式,当你删除一个项目,它不会影响你的循环。

+1

如果你提到这会产生一个输入的副本,这很好,这就是为什么你可以这样做。 :-) –

+0

酷感谢 - 这是一个伟大的方式做到这一点! –

+0

注意到Sam Mussmann。编辑答案提到为什么这个工程。 – SuperFamousGuy