问题描述
What's解决这一问题的最有效的,优雅的和Python的方式?
What´s the most efficient, elegant and pythonic way of solving this problem?
给出一个列表(或一组或其他)n个元素,我们希望得到k个最大的。 (你可以假定 K&n种/ 2
不失一般性,我猜)例如,如果列表是:
Given a list (or set or whatever) of n elements, we want to get the k biggest ones. ( You can assume k<n/2
without loss of generality, I guess)For example, if the list were:
l = [9,1,6,4,2,8,3,7,5]
N = 9,并假设K = 3。什么是最有效的算法用于检索的3个最大的呢?在这种情况下,我们应该得到 [9,8,7]
,没有特定的顺序。
n = 9, and let's say k = 3.What's the most efficient algorithm for retrieving the 3 biggest ones?In this case we should get [9,8,7]
, in no particular order.
谢谢!曼努埃尔
推荐答案
从heapq模块使用nlargest
Use nlargest from heapq module
from heapq import nlargest
lst = [9,1,6,4,2,8,3,7,5]
nlargest(3, lst) # Gives [9,8,7]
您也可以给一个关键的情况下nlargest你想改变你的标准:
You can also give a key to nlargest in case you wanna change your criteria:
from heapq import nlargest
tags = [ ("python", 30), ("ruby", 25), ("c++", 50), ("lisp", 20) ]
nlargest(2, tags, key=lambda e:e[1]) # Gives [ ("c++", 50), ("python", 30) ]
这篇关于如何有效地得到k个列表的蟒蛇更大的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!