2014-10-31 55 views
1

我試圖編寫一個讀取文件的代碼,然後返回文件中所有迴文列表。所以我創建了一個函數來檢查一個單詞是否是一個迴文,並且我試圖編寫另一個函數來讀取文件,擺脫空白區域,分割成單詞,然後測試每個單詞以查看它是否是一個迴文。如果它是一個迴文,那麼我將它添加到我將打印的列表中。但是,我收到一個錯誤「AttributeError:'元組'對象沒有屬性'append'」我怎樣才能得到添加到列表中的迴文?在文件中搜索palindromes並使用python打印它們列表

def findPalindrome(filename): 
    #an empty list to put palindromes into 
    list3 =() 
    #open the file 
    for line in open(filename): 
     #strip the lines of blank space 
     list1 = line.strip() 
     #Split the lines into words 
     list2 = line.split() 
     #call one of the words 
     for x in list2: 
      #test if it is a palindrome 
      if isPalindrome(x): 
       #add to list3 
       list3.append(x) 
    #return the list of palindromes 
    return list3 

回答

1

卸下:

list3=() # because it creates an empty tuple 

由:

list3=list() # create an empty list 

另外取代:

list2 = line.split() 

由:

list2 = list1.split() # because stripped line is in list1 not in line 
1

這裏的問題是,list3實際上不是一個列表。而不是做list3 =(),做list3 = []

()將創建一個tuple,這是一種類似於列表的數據結構,但在第一次創建後不能更改。這就是爲什麼你無法附加到它,因爲這會改變元組。 []創建一個實際的列表,這是一個可變的,可以隨着時間的推移而改變。

相關問題