2017-05-19 32 views
0

一個文件, 127,000+字被導入並列入列表Python:For循環在調用時減半我的列表

try: 
    dictionary = open("dictionary.txt", "r") 
except: 
    print("Dictionary not found") 
    exit() 
list_of_words = [word.rstrip('\n').rstrip('\r') for word in dictionary] 

當用戶輸入字長時,它會檢查以確保該單詞在參數內。

def length_check(x): 
    while(1): 
     x = int(input("Please enter a word length: ")) 
     if x >= 1 and x <=147: 
      return 
     else: 
      print ('enter proper length') 

,然後又把這個詞的長度並檢查它反對在列表中的單詞,並刪除列表中的任何字,那不是等於「word_length」

def read_and_delete(x): 
    i = 0 
    for removal in x: 
     if len(x[i]) != word_length: 
      del x[i] 
      i += 1 
     elif len(x[i]) == word_length: 
      i += 1 
     else: 
      continue 
    print(len(list_of_words)) 

但由於某些原因,輸出的結果恰好是列表中的一半,我不明白爲什麼代碼中沒有任何分隔。

+1

您在迭代它時將從列表中刪除項目。 –

回答

0

您正在執行遍歷列表並在同一時間修改它的錯誤。你應該總是避免這種情況。

在你的代碼中,del [i]創建一個間隙,然後移動數組中的所有後續數字,留下一個位置以填補間隙。當你增加i時,你跳過一個元素。

爲了完整,這將修復您的代碼。

def read_and_delete(x): 
    i = 0 
    for removal in x: 
     if len(x[i]) != word_length: 
      del x[i] 
     elif len(x[i]) == word_length: 
      i += 1 
     else: 
      continue 
    print(len(list_of_words)) 

這裏是做

def read_and_delete(x): 
    return [word for word in x if len(word) == word_length] 

這將返回一個新的列表,並且不改變以前一個更好的辦法。