Python 程序从列表中查找 N 个最大元素
programmingpythonserver side programming更新于 2025/3/15 2:52:17
在此示例中,我们将了解如何从列表中查找 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]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

