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 老爸吃饺子祝福语简短
11 周日徒步祝福语大全简短
12 店家搬家祝福语大全简短
13 送弟弟中秋祝福语简短
14 员工离职祝福语简短高级
15 家庭英语祝福语短句简短
16 文艺结婚祝福语短语简短
17 周年庆典祝福语致辞简短
18 父母生孩子祝福语简短