反转列表函数

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,可以使用内置函数对列表和字符串进行反转。不过,也可以使用切片表示法来反转列表或字符串。

在这个挑战中,你将编写一个使用切片表示法来反转列表或字符串的函数。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") subgraph Lab Skills python/comments -.-> lab-13709{{"反转列表函数"}} python/lists -.-> lab-13709{{"反转列表函数"}} python/tuples -.-> lab-13709{{"反转列表函数"}} python/function_definition -.-> lab-13709{{"反转列表函数"}} end

反转列表函数

编写一个名为 reverse(itr) 的 Python 函数,该函数接受一个列表或字符串作为参数,并返回一个新的列表或字符串,其中包含按相反顺序排列的元素或字符。

你的函数应满足以下要求:

  • 函数应命名为 reverse
  • 函数应接受单个参数,该参数是一个列表或字符串
  • 函数应返回一个新的列表或字符串,其中包含按相反顺序排列的元素或字符
  • 函数不应修改原始列表或字符串
def reverse(itr):
  return itr[::-1]
reverse([1, 2, 3]) ## [3, 2, 1]
reverse('snippet') ## 'teppins'

总结

在这个挑战中,你学习了如何在 Python 中使用切片表示法来反转列表或字符串。你编写了一个名为 reverse 的函数,该函数接受一个列表或字符串作为输入,并返回一个新的列表或字符串,其中包含按相反顺序排列的元素或字符。请记住,切片表示法可用于从列表或字符串中提取一系列元素。