Python程序在列表中查找第二大数字
在本文中,我们将学习下面给出的问题陈述的解决方案。
问题陈述 -我们得到一个列表,我们需要在列表中显示第二大数字。
有三种解决问题的方法-
方法1:我们使用set()函数和remove()函数
示例
list1 = [11,22,1,2,5,67,21,32]# to get unique elements
new_list = set(list1)
# removing the largest element from list1
new_list.remove(max(new_list))
# now computing the max element by built-in method?
print(max(new_list))
输出结果
32
方法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
结论
在本文中,我们了解了如何在列表中找到第二大元素。
以上是 Python程序在列表中查找第二大数字 的全部内容, 来源链接: utcz.com/z/355043.html