在文件中搜索回文并使用python将其打印到列表中
我试图写一段代码,读取一个文件,然后返回文件中所有回文的列表。所以我创建了一个函数来检查一个单词是否是回文,并且我试图编写另一个函数来读取文件,去掉空白,分割成单词,然后测试每个单词,看看它是否是回文。如果它是回文,那么我将它添加到最后打印的列表中。但是,我遇到了一个错误“AttributeError:‘tuple’对象没有属性‘append’”。如何将回文添加到此列表中在文件中搜索回文并使用python将其打印到列表中,python,list,append,text-files,Python,List,Append,Text Files,我试图写一段代码,读取一个文件,然后返回文件中所有回文的列表。所以我创建了一个函数来检查一个单词是否是回文,并且我试图编写另一个函数来读取文件,去掉空白,分割成单词,然后测试每个单词,看看它是否是回文。如果它是回文,那么我将它添加到最后打印的列表中。但是,我遇到了一个错误“AttributeError:‘tuple’对象没有属性‘append’”。如何将回文添加到此列表中 def findPalindrome(filename): #an empty list to put palind
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=[]
执行()
将创建一个类似于列表的数据结构类型,但在第一次创建后不能更改。这就是为什么不能附加到它,因为这会改变元组。[]
创建一个实际的列表,该列表是可变的,可以随时间而更改。删除:
list3=() # because it creates an empty tuple
作者:
还应替换:
list2 = line.split()
作者:
list2 = line.split()
list2 = list1.split() # because stripped line is in list1 not in line