Python比较运算符

aru*_*iat 0 python comparison-operators

我无法弄清楚为什么我的if-else语句没有按预期运行.我试图创建代码来测试回文字符串.我的打印功能向我显示反向方法有效,但是当我进入比较阶段时,我无法让它返回True.

这是代码:

def is_palindrome(a):
    myList = []

    for i in a:
        myList.append(i)

    print myList
    new = myList.reverse()
    print myList
    print new

    if myList == new:
        return True
    else:
        return False


print is_palindrome("radar")
Run Code Online (Sandbox Code Playgroud)

返回False.我也尝试将if语句更改为if myList is new:但不幸的是它仍然返回False.

有任何见解赞赏!

Dee*_*ace 5

list.reverse() 就地,意味着它反转它所调用的列表但不返回任何内容.

该行print new应打印None,因此myList == new将打印False.

相反,使用[::-1]不在原地并返回新的反向列表,或使用更简单的方法来检测回文,例如:

def is_palindrome(iterable):
    return iterable == iterable[::-1]
Run Code Online (Sandbox Code Playgroud)