为什么我的回文检查器找不到任何结果?
words = ['Anna', 'Alexey', 'Alla', 'Kazak', 'Dom']
def palindrome():
filtered_2 = list(filter(lambda x: x == x[::-1], words))
print(filtered_2)
palindrome()
该代码应返回palindrome单词,但它为我提供了这样的输出:
[]
它应该给出:
['Anna', 'Alla', 'Kazak']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果使用python> = 3.8,则可以使用:= )将原始单词保留在结果中,并且只有一个
.lower()
每个单词呼叫:If using Python >= 3.8, it is possible to use the walrus operator (
:=
) to keep the original words in the result and have only one.lower()
call per word:让我还强调一个事实,即函数的定义
palindrome
,就像您的代码中毫无意义,并且脚本在不定义函数的情况下完全相同:但是,如果您想用函数来制作函数是简单的方法:
这样,此代码
将返回您想要的结果。
Let me also highlight the fact that the definition of the function
palindrome
as in your code is pointless and the script would work exactly the same without defining the function:But if you want to make it with a function this is the simples way:
In this way this code
would return the results you want.
在比较之前,您需要将输入标准化。基本上,您正在检查
'a'=='a'
是否会失败。尝试使用
str.lower()
:You need to normalize the input before comparisons. Basically you are checking if
'A' == 'a'
which will fail.Try this example where I normalize to lowercase using
str.lower()
: