编写一个 Python 程序,通过实际示例按升序对列表进行排序。此 Python 程序允许用户输入任何整数值,我们将其视为列表的长度。接下来,我们使用 For 循环将数字添加到声明的列表中。
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.sort()
print("Element After Sorting List in Ascending Order is : ", NumList)
按升序对整数列表进行排序的输出
Please enter the Total Number of List Elements: 4
Please enter the Value of 1 Element : 56
Please enter the Value of 2 Element : 76
Please enter the Value of 3 Element : 44
Please enter the Value of 4 Element : 2
Element After Sorting List in Ascending Order is : [2, 44, 56, 76]
Python 程序,在不使用 Sort 的情况下按升序对列表进行排序
在此 程序中,我们使用嵌套的 For 循环来迭代列表中的每个数字,并按升序对它们进行排序。
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)
for i in range (Number):
for j in range(i + 1, Number):
if(NumList[i] > NumList[j]):
temp = NumList[i]
NumList[i] = NumList[j]
NumList[j] = temp
print("Element After Sorting List in Ascending Order is : ", NumList)
按升序对列表进行排序的输出。
Please enter the Total Number of List Elements: 4
Please enter the Value of 1 Element : 67
Please enter the Value of 2 Element : 86
Please enter the Value of 3 Element : 34
Please enter the Value of 4 Element : 55
Element After Sorting List in Ascending Order is : [34, 55, 67, 86]
第一个 Python For 循环 - 第一次迭代: for 0 in range(0, 4)
条件为 True。因此,它会进入第二个 for 循环
嵌套 For 循环 - 第一次迭代: for 1 in range(0 + 1, 4)
条件为 True。因此,它会进入 If 语句
if(NumList[0] > NumList[1]) = if(67 > 86) – 这意味着条件为 False。因此,它会退出 If 块,j 值会增加 1。
嵌套 For 循环 - 第二次迭代: for 2 in range(1, 4) – 条件为 True
if(67 > 34) – 条件为 True
temp = 67
NumList[i] = 34
NumList[j] = 67
现在列表为 = 34 86 67 55。接下来,j 增加 1。
嵌套 For 循环 - 第三次迭代: for 3 in range(1, 4) – 条件为 True
if(34 > 55) – 条件为 False。因此,它会退出 If 块,j 值为 4。
嵌套 For 循环 - 第四次迭代: for 4 in range(1, 4) – 条件为 False
接下来,i 值增加 1。
第一个 For 循环 - 第二次迭代: for 1 in range(0, 4)
条件为 True。因此,它会进入第二个 for 循环
对剩余的 Python 迭代执行相同的操作
Python 程序使用 While 循环按升序对列表进行排序
此列表项按升序排序的程序与上述相同。但是,我们用 While 循环替换了 For 循环。
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)
i = 0
while(i < Number):
j = i + 1
while(j < Number):
if(NumList[i] > NumList[j]):
temp = NumList[i]
NumList[i] = NumList[j]
NumList[j] = temp
j = j + 1
i = i + 1
print("Element After Sorting List in Ascending Order is : ", NumList)
