我有以下代码:
[x ** 2 for x in range(10)]
Run Code Online (Sandbox Code Playgroud)
当我在Python Shell中运行它时,它返回:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Run Code Online (Sandbox Code Playgroud)
我搜索过,似乎这被称为列表理解,但它是如何工作的?
我需要派生一个函数,它接受一个字符串并返回该字符串是否是回文并且我的函数应该在字符串上返回True如果不考虑空格(所以它应该说'一个人计划运河巴拿马'或'是我看到的'厕所'是'回文),但它不需要考虑大写字母或标点符号的变化(所以它可能会在"一个人,一个计划,一条运河 - 巴拿马!'上回归假,而'它是艾略特的'我看到厕所?').
我试过了
def palindrome(s):
return len(s) < 2 or s[0] == s[-1] and palindrome(s[1:-1])
Run Code Online (Sandbox Code Playgroud)
和
def ispalindrome(word):
if len(word) < 2: return True
if word[0] != word[-1]: return False
return ispalindrome(word[1:-1])
Run Code Online (Sandbox Code Playgroud)
但两者都不起作用.有什么建议?我正在使用python 3.3