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程序找到列表中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]