Python 如何反转列表中的对象
在Python中,列表是一个有序的序列,可以容纳多种对象类型,如整数,字符或浮点数。在其他编程语言中,列表等同于数组。
在本文中,我们将向您展示如何使用Python反转列表中的对象/元素。以下是实现此任务的4种不同方法:
- 使用内置的反转(reverse)方法
-
使用内建的reversed(反向)方法
-
使用切片(slicing)
-
使用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()函数向列表中添加元素。