簡體   English   中英

從列表列表中獲取前 n 個元素

[英]Get the n top elements from a list of lists

我將以下示例用於演示目的。

 [["apple",10],
 ["oranges",5],
 ["strawberies",2],
 ["pineapples",12],
 ["bananas",9],
 ["tomattoes",8],
 ["watermelon",1],
 ["mangos",7],
 ["grapes",11],
 ["potattoes",3]]

我想按數量說出前 3 種水果(返回的前 3 種元素),但是我不希望更改順序。 所以最終結果將是

[["apple",10],
 ["pineapples",12],
 ["grapes",11]]

任何幫助將不勝感激。

arr = [["apple",10],
 ["oranges",5],
 ["strawberies",2],
 ["pineapples",12],
 ["bananas",9],
 ["tomattoes",8],
 ["watermelon",1],
 ["mangos",7],
 ["grapes",11],
 ["potattoes",3]]

sorted_arr = sorted(arr,key=lambda x: x[1],reverse=True)[:3]
output = [elem for elem in arr if elem in sorted_arr]
print(sorted_arr)
print(output)

首先,我們以相反的順序對數組進行排序以獲得前 3 個元素。 然后,我們使用列表推導循環遍歷原始數組並檢查元素是否在前 3 位。這樣可以保留順序。

正如您之前可能聽說過的,有一種可以應用於列表的排序方法。 您可以將密鑰作為 function 傳遞,這將指示您希望如何對列表進行排序。

l = [["apple",10],
 ["oranges",5],
 ["strawberies",2],
 ["pineapples",12],
 ["bananas",9],
 ["tomattoes",8],
 ["watermelon",1],
 ["mangos",7],
 ["grapes",11],
 ["potattoes",3]]

l.sort(key = lambda x: x[1]) #to sort by second element
result = l[-3:] # To get the top three elements



         

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM