如何在 python 中使用过滤器函数的打印命令?

How to use the print command from a filter function in python?

我有一个作业要在 python 中编写一些代码来过滤回文。它应该是这样的:

enter image description here

这是我目前拥有的代码,但我无法让它打印出过滤和反转的用户输入:

palindrome=(input("Enter a sentence: "))
print("You typed in: ", palindrome)

def myFunc(s):
    r = ""
    for i in range(len(s)):
        c = s[i]
        if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z'):
            r += c.upper()
    return r

filtered = filter(myFunc, palindrome)
filtered2 = (filtered)

def isPalindrome(s):         #This string reverse code was take from https://www.geeksforgeeks.org/python-program-check-string-palindrome-not/
    return s == s[::-1]
s = palindrome
ans = isPalindrome(s)
if ans:
    print("Filtered:", filtered2)
    print("Reversed:", )
    print("It is a palindrome")
else:
    print("Filtered:", filtered2)
    print("Reversed:", )
    print("It is NOT a palindrome")

显示方式如下:

enter image description here

我missing/doing哪里错了?我很感激能提供的任何帮助。

我认为你不应该在这种情况下使用 filter。您可以直接使用 myFunc 输入。


palindrome=(input("Enter a sentence: "))
print("You typed in: ", palindrome)

def myFunc(s):
    r = ""
    for i in range(len(s)):
        c = s[i]
        if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z'):
            r += c.upper()
    return r

filtered = myFunc(palindrome)

def isPalindrome(s):        
    return s == s[::-1]

ans = isPalindrome(filtered)
if ans:
    print("Filtered:", filtered)
    print("Reversed:", filtered[::-1])
    print("It is a palindrome")
else:
    print("Filtered:", filtered)
    print("Reversed:", filtered[::-1])
    print("It is NOT a palindrome")

此外,如果您想打印 filter(myFunc, palindrome) 的结果,您必须先将其转换为 listtuple 以查看其中的内容。

In [11]: x = filter(lambda x:x%3, [1,2,3,4,5,6])                                                                                                                                

In [12]: print(x)                                                                                                                                                               
<filter object at 0x7f9c4014d580>

In [13]: print(list(x))                                                                                                                                                         
[1, 2, 4, 5]