2013-09-26 33 views
0

正在從本書的思考python中嘗試此練習。 編寫一個從文件中讀取單詞列表的程序(參見9.1節),並打印所有字母集合。Think Python Ch12 Ex 4:代碼看起來正確但編譯時掛起

我的策略是獲取文件,對每個單詞進行排序並存儲在一個字符串列表(稱爲listy)中。然後,我會再次查看單詞的原始列表,並與listy進行比較。如果相同,則將已排序的單詞作爲鍵和未排序的單詞從原始文件存儲爲字典中的值。然後只需打印出每個鍵下的所有值。他們應該是anagrams。

我創建的第一個函數是生成listy。已經打破了代碼,並檢查它,似乎很好。但是,當我編譯並運行它時,python會掛起,就像遇到無限循環一樣。誰能告訴我這是爲什麼?

def newlist(): 
    fin = open('words.txt') 
    listy = [] 
    for word in fin: 
     n1 = word.strip() 
     n2 = sorted(n1) 
     red = ''.join(n2) 
     if red not in listy: 
      listy.append(red) 

    return listy 

newlist() 
+0

我無法重現的竅門。你能顯示有問題的words.txt嗎? – rerx

回答

0

使用set檢查單詞是否已經preocessed與否:

def newlist(): 
    with open('words.txt') as fin: 
     listy = set() 
     for word in fin: 
      n1 = word.strip() 
      n2 = sorted(n1) 
      red = ''.join(n2) 
      listy.add(red) 
    return listy 

newlist() 

你甚至可以把它寫成:

def newlist(): 
    with open('words.txt') as fin: 
     return set(''.join(sorted(word.strip())) for word in fin) 

newlist()