当我们的列表中有很多元素时,想要找到最高或最低的元素可能会浮现在我们的脑海中,Python已经为我们大大简化了这个过程。

在本文中,我们将学习如何从列表中使用Python找到第二大的数字。

  1. 对列表进行排序,然后打印倒数第二个数字。
  2. 删除最大元素。
  3. 查找最大元素。
  4. 遍历列表。

让我们首先看一下第一种方法:

对列表进行排序,然后打印倒数第二个数字

以下程序说明了如何在Python中执行此操作:

示例 -

#program to find the second largest number of list  
# declaring the list  
list_val = [20, 30, 40, 25, 10]  
# sorting the list  
list_val.sort()  
#displaying the second last element of the list  
print("The second largest element of the list is:", list_val[-2])  

输出:

The second largest element of the list is: 30

现在让我们进行解释:

  1. 我们已经声明了一个列表,我们要从中获取倒数第二个元素。
  2. 然后,我们使用sort方法,以便将列表的所有元素按升序排列。
  3. 现在我们使用负索引,因为第二大的数字将出现在倒数第二个位置。

第二种方法是通过删除最大元素来获取列表中的第二大元素。

让我们看看如何做到这一点。

删除最大元素

示例 -

#program to find the second largest number of list  
  
# declaring the list  
list_val = [20, 30, 40, 25, 10]  
  
# new_list is a set of list1  
res_list = set(list_val)  
  
#removing the maximum element  
res_list.remove(max(res_list))  
  
#printing the second largest element   
print(max(res_list))  

输出:

30

解释 -

让我们了解一下上面的程序中我们做了什么:

  1. 我们已经声明了一个列表,我们要从中获取倒数第二个元素。
  2. 然后,我们使用set方法获取列表的所有唯一元素。
  3. 现在我们使用max()从列表中获取最大值,然后将其删除。
  4. 然后,我们打印结果列表的最大值,这将给我们第二大的数字。

在第三种方法中,我们将使用for循环并遍历列表,然后使用条件语句来找出列表中的第二大元素。

示例 -

# declaring empty list  
list_val = []  
  
# user provides the number of elements to be added in the list  
num_list = int(input("Enter number of elements in list: "))  
  
  
for i in range(1, num_list + 1):  
    element = int(input("Enter the elements: "))  
    list_val.append(element)  
  
  
# sort the list  
list_val.sort()  
      
# print second largest element  
print("Second largest element is:", list_val[-2])  

输出:

Enter number of elements in list: 5

Enter the elements: 10

Enter the elements: 20

Enter the elements: 30

Enter the elements: 40

Enter the elements: 50
The second largest element is: 40

解释 -

让我们了解一下我们在这里做了什么:

  1. 我们声明了一个空列表,我们将在其中插入元素。
  2. 然后,我们要求用户提供要添加到我们的列表中的元素数量。
  3. 然后,我们使用sort方法,以便将列表的所有元素按升序排列。
  4. 现在我们使用负索引,因为第二大的数字将出现在倒数第二个位置。

遍历列表

在最后一个程序中,我们将遍历列表以找出最大的数字,然后使用条件语句来找出列表中的第二大元素。

以下程序说明了相同的内容:

示例 -

def calc_largest(arr):  
    second_largest = arr[0]  
    largest_val = arr[0]  
    for i in range(len(arr)):  
        if arr[i] > largest_val:  
            largest_val = arr[i]  
  
    for i in range(len(arr)):  
        if arr[i] > second_largest and arr[i] != largest_val:  
            second_largest = arr[i]  
  
    return second_largest  
print(calc_largest([20, 30, 40, 25, 10]))  

输出:

30

解释 -

让我们了解一下上面的程序中我们做了什么:

  1. 第一步是创建一个函数,通过遍历来检查列表中的最大数字。
  2. 在下一个for循环中,我们再次遍历列表以找到最大的数字,但这次排除了前一个数字,因为这里我们的目标是找到第二大的数字。
  3. 最后,我们将我们的列表传递给函数。

因此,在本文中,我们有机会突破思维定势,发现了一些新方法来开发在Python中找到第二大数字的逻辑。

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程