查詢列表中第二大數字的 Python 程式


在本文中,我們將學習以下給定問題語句的解決方案。

問題語句 - 給定一個列表,我們需要顯示該列表中第二大的數字。

有三種方法可以解決此問題 -

方法 1 - 我們使用 set() 函式和 remove() 函式

示例

 即時演示

list1 = [11,22,1,2,5,67,21,32]
# to get unique elements
new_list = set(list1)
# removing the largest element from list1
new_list.remove(max(new_list))
# now computing the max element by built-in method?
print(max(new_list))

輸出

32

方法 2 - 我們使用 sort() 方法和負數索引

示例

 即時演示

list1 = [11,22,1,2,5,67,21,32]
# using built-in sort method
list1.sort()
# second last element
print("Second largest element in the list is:", list1[-2])

輸出

Second largest element in the list is: 32

方法 3 - 我們使用蠻力法來獲取第二大元素

示例

 即時演示

list1 = [11,22,1,2,5,67,21,32]
#assuming max_ is equal to maximum of element at 0th and 1st index
and secondmax is the minimum among them
max_=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
for i in range(2,len(list1)):
   # if found element is greater than max_
   if list1[i]>max_:
      secondmax=max_
      max_=list1[i]
   #if found element is greator than secondmax
   else:
      if list1[i]>secondmax:
         secondmax=list1[i]
print("Second highest number is the list is : ",str(secondmax))

輸出

Second highest number is the list is : 32

結論

在本文中,我們學習瞭如何查詢列表中第二大的元素。

更新於: 2020‎年‎7月‎11日

4K+ 次瀏覽

啟動你的職業

完成課程後獲得認證

開始
廣告