寫一個 Python 程序,用一個實際例子找出列表中的第二大數字。
Python 程序在列表中查找第二大數字示例 1
這個 python 程序允許用戶輸入長度。接下來,我們使用 For 循環在 Python 中向列表中添加數字。
python 中的排序函數以升序對列表元素進行排序。接下來,我們使用 Python 索引位置來打印列表中的最後一個元素。
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("The Largest Element in this List is : ", NumList[Number - 2])
Python 程序在列表中查找第二大數字示例 2
這個程序按照升序對元素進行排序。接下來,我們使用反轉功能來反轉列表項。最後,我們使用索引位置 1 來打印列表中的第二個元素。
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()
NumList.reverse()
print("The Largest Element in this List is : ", NumList[1])
Please enter the Total Number of List Elements: 5
Please enter the Value of 1 Element : 20
Please enter the Value of 2 Element : 56
Please enter the Value of 3 Element : 78
Please enter the Value of 4 Element : 97
Please enter the Value of 5 Element : 60
The Largest Element in this List is : 78
Python 程序在列表中查找第二大數字示例 3
在這個程序中,我們沒有使用任何內置功能,比如排序或者反轉功能。為此,我們使用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)
first = second = NumList[0]
for j in range(1, Number):
if(NumList[j] > first):
second = first
first = NumList[j]
elif(NumList[j] > second and NumList[j] < first):
second = NumList[j]
print("The Largest Element in this List is : ", first)
print("The Second Largest Element in this List is : ", second)
Please enter the Total Number of List Elements: 4
Please enter the Value of 1 Element : 55
Please enter the Value of 2 Element : 57
Please enter the Value of 3 Element : 22
Please enter the Value of 4 Element : 3
The Largest Element in this List is : 57
The Second Largest Element in this List is : 55
從上面的 Python 程序返回列表截圖中的第二大數字,可以觀察到用戶插入的值是
NumList[4] = {55,57,22,3}
第一個=第二個= NumList[0] = 55
第一次迭代–對於範圍(1,4)中的 1–條件為真
因此,它開始在循環內執行 If 語句,直到條件失敗。
如果 for 循環內的(NumList[j] > first)為 True,因為(57>55)
first = first = 55
first = NumList[1]= 57
第二次迭代:對於範圍(1,4)中的 2–條件為真
如果(NumList[2] >優先)=(22>57)–條件為假。因此,它進入 elif 語句
elif(NumList[2] >第二,NumList[2] <第一)
elif(22 > 55 和 22<57)–條件為假
第三次迭代:對於範圍(1,4)中的 3–條件為真
如果(3>57)–條件為假
elif(3 > 55 和 3<57)–條件為假
第四次迭代:對於範圍(1,4)中的 4–條件為假。所以,它從循環中退出。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/297336.html