您的位置:

Python 程序:反转列表

写一个 Python 程序,用一个实际的例子来反转列表项或列表元素。

反转列表项目的 Python 程序

它允许用户输入列表的长度。接下来,我们使用 Python For Loop 向列表中添加数字。

NumList = []

Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
    value = int(input("Please enter the Value of %d Element : " %i))
    NumList.append(value)

NumList.reverse()
print("\nThe Result of a Reverse List =  ", NumList)

提示: Python 函数用于反转列表中的元素。

在这个 python 程序中,我们使用了一个 While 循环。在 while 循环中,我们在第三个变量的帮助下执行了交换。我建议你参考互换两个数字的文章来理解 Python 的逻辑。

NumList = []

Number = int(input("Please enter the Total Numbers : "))
for i in range(1, Number + 1):
    value = int(input("%d Element : " %i))
    NumList.append(value)

j = Number - 1
i = 0

while(i < j):
    temp = NumList[i]
    NumList[i] = NumList[j]
    NumList[j] = temp
    i = i + 1
    j = j - 1

print("\nThe Result =  ", NumList)
Please enter the Total Numbers : 3
1 Element : 1
2 Element : 2
3 Element : 3

The Result =   [3, 2, 1]

使用函数在 Python 中反转列表的程序

本列表项目程序同上。然而,我们使用函数 来分离逻辑

def reverseList(NumList, num):
    j = Number - 1
    i = 0
    while(i < j):
        temp = NumList[i]
        NumList[i] = NumList[j]
        NumList[j] = temp
        i = i + 1
        j = j - 1

NumList = []
Number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, Number + 1):
    value = int(input("%d Element : " %i))
    NumList.append(value)

reverseList(NumList, Number)
print("\nThe Result =  ", NumList)
Please enter the Total Number of Elements: 5
1 Element : 10
2 Element : 20
3 Element : 30
4 Element : 40
5 Element : 50

The Result =   [50, 40, 30, 20, 10]

这个程序通过递归调用函数来反转列表项

def reverseList(NumList, i, j):
    if(i < j):
        temp = NumList[i]
        NumList[i] = NumList[j]
        NumList[j] = temp
        reverse_list(NumList, i + 1, j-1)

NumList = []
Number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, Number + 1):
    value = int(input("%d Element : " %i))
    NumList.append(value)

reverseList(NumList, 0, Number - 1)
print("\nThe Result =  ", NumList)
Please enter the Total Number of Elements: 6
1 Element : 12
2 Element : 13
3 Element : 14
4 Element : 15
5 Element : 16
6 Element : 27

The Result =   [27, 16, 15, 14, 13, 12]