【问题标题】:Searching a file for palindromes and printing them in a list with python在文件中搜索回文并使用 python 在列表中打印它们
【发布时间】:2014-12-28 00:00:34
【问题描述】:

我正在尝试编写一个代码来读取文件,然后返回文件中所有回文的列表。所以我创建了一个函数来检查一个单词是否是回文,并且我尝试编写另一个函数来读取文件,摆脱空格,拆分成单词,然后测试每个单词以查看它是否是回文。如果它是回文,那么我将它添加到我将在最后打印的列表中。但是,我收到一个错误“AttributeError: 'tuple' object has no attribute '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

【问题讨论】:

    标签: python list append text-files


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      这里的问题是list3 实际上并不是一个列表。不要做list3 = (),而是做list3 = []

      执行() 将创建tuple,这是一种类似于列表的数据结构,但在首次创建后无法更改。这就是为什么您无法附加到它的原因,因为这会改变元组。 [] 创建一个实际的列表,该列表是可变的并且可以随着时间而改变。

      【讨论】:

        猜你喜欢
        • 2012-03-10
        • 1970-01-01
        • 2011-06-14
        • 1970-01-01
        • 1970-01-01
        • 2021-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多