mySentence = "Mary had a little lamb"
def reverseSentence(text):
# split the text
listOfWords = text.split()
#reverese words order inside sentence
listOfWords.reverse()
#reverse each word inside the list using map function(Better than doing loops...)
listOfWords = list(map(lambda x: x[::-1], listOfWords))
#return
return listOfWords
print(reverseSentence(mySentence))
切片表示法的第二个参数表示“最多,但不包括”,因此
sentence[length:0:-1]
将循环到0,但不在0处。你知道吗解决方法是显式地将0更改为-1,或者忽略它(首选)。你知道吗
试试这个:使用MAP函数没有循环
您需要从索引范围中删除
0
,但可以使用:也不是说你不需要循环你的字符串和使用额外的赋值,甚至
length
你也可以简单地打印反转的字符串。你知道吗因此,以下代码将为您完成这项工作:
演示:
相关问题 更多 >
编程相关推荐