我试图获取一个文本文件,将其转换为一个列表,然后要求用户输入单词长度。我的函数应该打印文本文件中的所有回文。我的输出只是一个空列表。有什么建议吗?在
def main():
size = int(input('Enter word size:')
printPal(size)
def readFile():
L = open('scrabble_wordlist.txt', 'r')
words = L.read()
L.close()
while ' ' in words:
words.remove(' ')
wordlist = words.split()
return(wordlist)
def printPal(size):
L = readFile()
results = []
for word in L:
if isPal(word) and len(word) == size:
results.append(word)
return(results)
def isPal(word):
return word == reversed(word)
您可以这样做:
如果您愿意,可以将其简化为一行:
^{pr2}$将字符串转换为字符列表不会使用
split()
:是什么让你认为你的输出是一个空列表?您忽略了
printPal
的输出,因为没有保存它(或打印它或其他任何东西)。尝试将main
更改为并且确保你以后发布的代码是准确的。您在上面的一行中缺少右括号,并且没有调用
main
。在相关问题 更多 >
编程相关推荐