如何在 Python 中反转列表中的对象?
在 Python 中,列表是一个有序序列,可以保存多种对象类型,例如整数、字符或浮点数。在其他编程语言中,列表相当于数组。
在本文中,我们将向您展示如何使用 Python 反转列表中的对象/元素。以下是完成此任务的 4 种不同方法 -
使用内置的 reverse() 方法
使用内置的 reversed() 方法
使用切片
使用 For 循环、pop() 和 append() 函数
假设我们已经获取了一个包含一些元素的列表。使用上述不同方法反转输入列表的所有项目后,我们将返回一个新列表。
方法 1:使用内置的 reverse() 方法
算法(步骤)
以下是执行所需任务需要遵循的算法/步骤 -
创建一个变量来存储输入列表。
使用reverse()函数将列表的所有项目反转,方法是将其应用于输入列表。
reverse() 方法反转列表中的项目。此函数不接受任何参数。
reverse() 方法不返回任何内容。它更新现有列表。
反转输入列表项后打印结果列表
示例
以下程序在使用 reverse() 方法反转输入列表的所有项后返回结果列表 -
# input list demoList = [4, 7, 2, 1, 6] # reversing the list items demoList.reverse() # printing the list after reversing list items print('The output list after reversing:', demoList)
输出
执行时,上述程序将生成以下输出 -
The output list after reversing: [6, 1, 2, 7, 4]
方法 2:使用内置的 reversed() 方法
reversed() 方法以列表的形式返回给定序列对象的反转
语法
reversed(sequence)
算法(步骤)
以下是执行所需任务需要遵循的算法/步骤 -
创建一个变量来存储输入列表。
使用 reversed() 函数()通过将列表作为参数传递给它来反转输入列表的所有项目,然后使用 list() 函数将结果转换为列表(Python 中的 list() 方法接受任何可迭代对象作为参数并返回列表)
打印结果列表后反转输入列表项。
示例
以下程序在使用 reversed() 方法反转输入列表的所有项后返回结果列表 -
# input list demoList = [4, 7, 2, 1, 6] # reversing the list items and converting the result into # list using list() function reversedList = list(reversed(demoList)) # printing the list after reversing list items print('The output list after reversing:', reversedList)
输出
The output list after reversing: [6, 1, 2, 7, 4]
方法 3:使用切片
算法(步骤)
以下是执行所需任务所要遵循的算法/步骤 -
创建一个变量来存储输入列表。
使用切片方法反转输入列表的所有项目并创建一个变量来存储它。
反转输入列表项后打印结果列表。
语法
reversedList = demoList[::-1]
此处'::-1'表示我们从末尾开始以相反的顺序逐个元素开始(负切片)。
示例
以下程序在使用切片反转输入列表的所有项目后返回结果列表 -
# input list demoList = [4, 7, 2, 1, 6] # reversing the list items using slicing reversedList = demoList[::-1] # printing the list after reversing list items print('The output list after reversing:', reversedList)
输出
The output list after reversing: [6, 1, 2, 7, 4]
方法 4:使用 For 循环、pop() 和 append() 函数
算法(步骤)
以下是执行所需任务所要遵循的算法/步骤 -
创建一个变量来存储输入列表。
创建一个空列表以相反的顺序存储列表项
使用 for 循环,使用 len()函数遍历列表的每个元素直到最后(对象中的项目数由 len() 方法返回)。
使用 pop() 函数删除最后一个列表元素(从列表中删除最后一个元素并返回它),并使用 append() 函数将其附加到上面的结果列表中(将元素添加到列表中结束)。
反转输入列表项后打印结果列表。
示例
以下程序在使用 for 循环、pop 和 append() 函数反转输入列表的所有项后返回结果列表 -
# input list demoList = [4, 7, 2, 1, 6] # storing the list items in reverse order reversed_list = [] # Traversing through each element of the list till the end for i in range(len(demoList)): # removing the last list element and appending it to the empty list reversed_list.append(demoList.pop()) # printing the list after reversing list items print('The output list after reversing:', reversed_list)
输出
执行时,上述程序将生成以下输出 -
The output list after reversing: [6, 1, 2, 7, 4]
我们给出了一个包含一些随机数据的列表。然后我们使用另一个空列表来包含原始列表的反转值。然后,使用 for 循环遍历列表的长度并从列表中弹出元素,pop() 函数将从最后一个列表中删除元素,然后使用 append 函数将弹出的元素放入反转列表中。最后,我们反向打印列表。
结论
在本教程中,我们学习了如何使用四种不同的方法反转列表的元素/对象。我们学习了如何使用函数 reverse() 和 reversed()。我们确定了如何使用负切片以相反的顺序获取所有元素。我们还学习了如何使用 pop() 方法从列表中删除元素以及如何使用 append() 函数将元素添加到列表中
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

