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

结论

在本文中,我们了解了如何在字典中找到第二个最大值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值