python找出第二大值,Python程序在Dictionary中查找第二个最大值
在本文中,我們將學習下面給出的問題陳述的解決方案。
問題陳述-我們給了兩個整數,我們需要在字典中打印第二個最大值
現在讓我們觀察一下下面的實現中的概念-
方法1:sorted()通過負索引使用函數
示例#input
example_dict?={"tutor":3,?"tutorials":15,
"point":9,"nhooo":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("列表中的第二大元素是:",?list1[-2])
輸出結果列表中的第二大元素是:?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
結論
在本文中,我們了解了如何在字典中找到第二個最大值。
總結
以上是生活随笔為你收集整理的python找出第二大值,Python程序在Dictionary中查找第二个最大值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 命名空间地址,php命名空间简介
- 下一篇: 小象钱包二次认证签约稳了吗