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]
廣告