用一個實例編寫一個 Python 程序,對列表進行升序排序。
按升序排序列表的 Python 程序
這個 python 程序允許用戶輸入任何整數值,我們認為它是一個列表的長度。接下來,我們使用 For 循環向 Python 列表添加數字。
Python 排序功能按照升序對列表項進行排序。
# Python Program to Sort List in Ascending Order
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)
以升序輸出對 Python 列表進行排序
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 程序以升序排序列表而不使用排序
在這個程序中,我們使用嵌套 For 循環來迭代列表中的每個數字,並按升序排序。
# Python Program to Sort List in Ascending Order
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)
以升序輸出對 Python 列表進行排序
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 Loop–第一次迭代:對於範圍(0,4)
中的 0,條件為真。因此,它進入第二個 for 循環
嵌套循環–第一次迭代:對於範圍(0 + 1,4)中的 1,
條件為真。於是,進入 If 語句
if(NumList[0]> NumList[1])= if(67 > 86)–表示條件為 False。因此,它從 If 塊退出,j 值增加 1。
嵌套循環–第二次迭代:對於範圍(1,4)中的 2–條件為真
如果(67>34)–條件為真
溫度= 67
數值列表[i] = 34
數值列表[j] = 67
現在列表= 34 86 67 55。接下來,j 遞增 1。
嵌套循環–第三次迭代:範圍(1,4)中的 3–條件為真
如果(34 > 55)–條件為假。因此,它從 If 塊退出,j 值為 4。
嵌套循環–第四次迭代:對於範圍(1,4)中的 4–條件為假
接下來,I 值增加 1。
第一次循環–第二次迭代:對於範圍(0,4)
中的 1,條件為真。因此,它進入第二個循環
對剩餘的 Python 迭代執行相同的操作
使用 While 循環對列表進行升序排序的 Python 程序
這個以升序排序列表項的 Python 程序與上面相同。然而,我們將 For Loop 替換為 While loop 。
# Python Program to Sort List in Ascending Order
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)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/244155.html