簡體   English   中英

在文件中搜索回文,並使用python將其打印在列表中

[英]Searching a file for palindromes and printing them in a list with python

我試圖編寫代碼來讀取文件,然后返回文件中所有回文列表。 因此,我創建了一個函數來檢查一個單詞是否是回文,並且我嘗試編寫另一個函數來讀取文件,擺脫空格,拆分成單詞,然后測試每個單詞以查看它是否是一個回文。回文。 如果是回文,則將其添加到最后要打印的列表中。 但是,我收到一個錯誤“ AttributeError:'tuple'對象沒有屬性'append'”如何將回文添加到此列表中?

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

這里的問題是list3實際上不是列表。 而不是執行list3 = () ,而是執行list3 = []

Doing ()將創建一個tuple ,它是一種類似於列表的數據結構,但是在首次創建后就不能更改。 這就是為什么您無法附加到它的原因,因為那樣會改變元組。 []創建一個實際的列表,該列表是可變的,可以隨時間更改。

去掉:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM