2012-11-29 49 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