首页 > 解决方案 > 未附加列表

问题描述

我需要打开一个 .txt 文件并遍历它以寻找回文。我的循环将遍历文件,但没有返回任何内容,即使我知道文件中有回文。当我运行它时,它只会打印出一堆空括号。

file = open("dictionary.txt", "r") 
lst = [] 
for word in file: 
    if(len(word) > 1 and word == word[::-1]): 
        lst = lst.append(word) 
    print(lst)

标签: pythonlistloopsappend

解决方案


你应该strip你的字符串。此外,append修改原始列表并返回None.

file = open("dictionary.txt", "r") 
lst = [] 
for word in file:
    word=word.strip()
    if(len(word) > 1 and word == word[::-1]): 
        lst.append(word) 
print(lst)

推荐阅读