Python求列表中最大,最小,第二大,第二最小值

2021年4月11日15:54:37 发表评论 768 次浏览

由于与其他编程语言不同, Python没有数组, 而是拥有列表。与数组相比, 使用列表更易于使用。而且, Python内置的庞大功能使任务变得更加容易。因此, 使用这些技术, 我们尝试在给定列表中查找数字的各种范围。

例子:

Input : list = [12, 45, 2, 41, 31, 10, 8, 6, 4]
Output : 
Largest element is: 45
Smallest element is: 2
Second Largest element is: 41
Second Smallest element is: 4

Input : list = [22, 85, 62, 40, 55, 12, 39, 2, 43]
Output :
Largest element is: 85
Smallest element is: 2
Second Largest element is: 62
Second Smallest element is: 12

该方法很简单。 Python允许我们使用list()函数对列表进行排序。使用此方法, 我们可以在对列表进行排序后从该位置找到列表中的各种数字范围。像第一个位置必须包含最小的元素, 最后一个元素必须包含最大的元素。

# Python prog to illustrate the following in a list
def find_len(list1):
     length = len (list1)
     list1.sort()
     print ( "Largest element is:" , list1[length - 1 ])
     print ( "Smallest element is:" , list1[ 0 ])
     print ( "Second Largest element is:" , list1[length - 2 ])
     print ( "Second Smallest element is:" , list1[ 1 ])
  
# Driver Code
list1 = [ 12 , 45 , 2 , 41 , 31 , 10 , 8 , 6 , 4 ]
Largest = find_len(list1)

输出如下:

Largest element is: 45
Smallest element is: 2
Second Largest element is: 41
Second Smallest element is: 4

下面是进行以下计算的另一种传统方法。该算法很简单, 我们将一个数字与列表中存在的所有其他数字进行比较, 然后得出最大, 最小, 第二大和第二最小的元素。

# Python program to find largest, smallest, # second largest and second smallest in a
# list with complexity O(n)
def Range (list1): 
     largest = list1[ 0 ] 
     lowest = list1[ 0 ] 
     largest2 = None
     lowest2 = None
     for item in list1[ 1 :]:     
         if item> largest: 
             largest2 = largest
             largest = item 
         elif largest2 = = None or largest2 <item: 
             largest2 = item 
         if item <lowest: 
             lowest2 = lowest
             lowest = item 
         elif lowest2 = = None or lowest2> item: 
             lowest2 = item 
              
     print ( "Largest element is:" , largest) 
     print ( "Smallest element is:" , lowest) 
     print ( "Second Largest element is:" , largest2) 
     print ( "Second Smallest element is:" , lowest2) 
  
  
# Driver Code
list1 = [ 12 , 45 , 2 , 41 , 31 , 10 , 8 , 6 , 4 ]
Range (list1)

输出如下:

Largest element is: 45
Smallest element is: 2
Second Largest element is: 41
Second Smallest element is: 4

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: