Python程式查詢字典中第二大值
在本文中,我們將學習以下問題陳述的解決方案。
問題陳述 - 給定兩個整數,我們需要列印字典中的第二大值
現在讓我們在下面的實現中觀察這個概念 -
方法 1 - 使用帶負索引的sorted()函式
示例
#input
example_dict ={"tutor":3, "tutorials":15,
"point":9,"tutorialspoint":19}
# sorting the given list and get the second last element
print(list(sorted(example_dict.values()))[-2])輸出
15
方法 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
結論
在本文中,我們學習瞭如何在字典中找到第二大值)。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP