Python中回文列表与反转后列表判定不等问题排查
问题原因及解决方法
核心问题
你的代码里用到的list.reverse()方法是原地修改列表——它会直接把原列表反转,但这个方法的返回值是None。所以你写的word_check == word_check.reverse(),本质是在比较原列表和None,这两个永远不可能相等,哪怕输入的是回文字符串,结果也会是否定的。
举个例子:输入THHT时,word_check初始是['T','H','H','T'],调用reverse()后,word_check本身变成['T','H','H','T'](因为是回文,反转后和原列表一致),但reverse()返回的是None,所以判断条件实际是['T','H','H','T'] == None,结果必然是False,所以输出否定。
解决方法
有几种简洁的修正方式:
- 用切片生成反转副本(推荐)
切片[::-1]会生成原列表/字符串的反转副本,不修改原内容,直接比较即可:
word = input("Input a word: ") word_check = list(word) if word_check == word_check[::-1]: print("The word is a palindrome") else: print("The word is not a palindrome")
- 直接比较字符串(更简洁)
其实不需要转成列表,字符串同样支持切片反转,代码更短:
word = input("Input a word: ") if word == word[::-1]: print("The word is a palindrome") else: print("The word is not a palindrome")
- 先反转再比较(不推荐)
如果一定要用reverse(),可以先调用它修改原列表,再和原字符串转成的列表比较:
word = input("Input a word: ") word_check = list(word) word_check.reverse() if word_check == list(word): print("The word is a palindrome") else: print("The word is not a palindrome")
内容的提问来源于stack exchange,提问作者krzys_13
相关产品推荐
相关产品推荐

