Python程序交换列表的首尾元素
在本文中,我们将学习如何解决下面给出的问题。
问题陈述 − 给定一个列表,我们需要将最后一个元素与第一个元素交换。
下面讨论了四种解决此问题的方法:
方法一 - 暴力方法
示例
def swapLast(List): size = len(List) # Swap operation temp = List[0] List[0] = List[size - 1] List[size - 1] = temp return List # Driver code List = ['t','u','t','o','r','i','a','l'] print(swapLast(List))
输出
['t','u','t','o','r','i','a','l']
方法二 - 使用负索引的暴力方法
示例
def swapLast(List): size = len(List) # Swap operation temp = List[0] List[0] = List[-1] List[-1] = temp return List # Driver code List = ['t','u','t','o','r','i','a','l'] print(swapLast(List))
输出
['t','u','t','o','r','i','a','l']
方法三 - 元组的打包和解包
示例
def swapLast(List): #packing the elements get = List[-1], List[0] # unpacking those elements List[0], List[-1] = get return List # Driver code List = ['t','u','t','o','r','i','a','l'] print(swapLast(List))
输出
['t','u','t','o','r','i','a','l']
方法四 - 元组的打包和解包
示例
def swapLast(List): #packing the elements start, *middle, end = List # unpacking those elements List = [end, *middle, start] return List # Driver code List = ['t','u','t','o','r','i','a','l'] print(swapLast(List))
输出
['t','u','t','o','r','i','a','l']
结论
在本文中,我们学习了如何在列表中交换首尾元素。
广告