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