Python程序查找列表中的N个最大元素
在这个例子中,我们将了解如何从列表中找到N个最大的元素。列表是Python中最通用的数据类型,可以写成方括号之间用逗号分隔的值(项)的列表。列表的一个重要特点是,列表中的项不必是相同类型。
假设以下为输入列表:
[25, 18, 29, 87, 45, 67, 98, 5, 59]
以下是显示列表中N个最大元素的输出。这里,N = 3:
[98, 87, 67]
Python程序使用for循环查找列表中的N个最大元素
我们将在这里使用for循环来查找列表中的N个最大元素:
示例
def LargestFunc(list1, N): new_list = [] for i in range(0, N): max1 = 0 for j in range(len(list1)): if list1[j] > max1: max1 = list1[j]; list1.remove(max1); new_list.append(max1) print("Largest numbers = ",new_list) # Driver code my_list = [12, 61, 41, 85, 40, 13, 77, 65, 100] N = 4 # Calling the function LargestFunc(my_list, N)
输出
Largest numbers = [100, 85, 77, 65]
Python程序使用sort()函数查找列表中的N个最大元素
我们将使用内置函数sort()来查找列表中的N个最大元素:
示例
# Create a List myList = [120, 50, 89, 170, 45, 250, 450, 340] print("List = ",myList) # The value of N n = 4 # First, sort the List myList.sort() # Now, get the largest N integers from the list print("Largest integers from the List = ",myList[-n:])
输出
List = [120, 50, 89, 170, 45, 250, 450, 340] Largest integers from the List = [170, 250, 340, 450]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP