I'd like to create a list maxValues containing top 20 values from a list of integers lst.
我想从整数列表lst创建一个包含前20个值的列表maxValues。
maxValues = []
for i in range(20):
maxValues.append(max(lst))
lst.remove(max(lst))
Is there a more compact code for achieving this task or even built-in function?
是否有更紧凑的代码来实现此任务甚至内置功能?
2 个解决方案
#1
12
There's heapq.nlargest()
:
maxvalues = heapq.nlargest(20, lst)
From the doc:
从文档:
heapq.nlargest(n, iterable, key=None)
heapq.nlargest(n,iterable,key = None)
Return a list with the n largest elements from the dataset defined by
iterable
.key
, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable:key=str.lower
Equivalent to:sorted(iterable, key=key, reverse=True)[:n]
返回一个列表,其中包含iterable定义的数据集中的n个最大元素。 key(如果提供)指定一个参数的函数,该函数用于从iterable中的每个元素中提取比较键:key = str.lower等效于:sorted(iterable,key = key,reverse = True)[:n]
Or at the same way use heapq.nsmallest()
if you want the smallest.
或者以相同的方式使用heapq.nsmallest(),如果你想要最小的。
IMPORTANT NOTE from the doc:
来自doc的重要说明:
The latter two functions [
nlargest
andnsmallest
] perform best for smaller values ofn
. For larger values, it is more efficient to use thesorted()
function. Also, whenn==1
, it is more efficient to use the built-inmin()
andmax()
functions.后两个函数[nlargest和nsmallest]对较小的n值表现最佳。对于更大的值,使用sorted()函数更有效。此外,当n == 1时,使用内置的min()和max()函数效率更高。
#2
6
sorted(lst)[-20:]
is the shortest I can think of. Likely to be faster, too.
是我能想到的最短的。也可能更快。
(edited: first try found the min instead of the max)
(编辑:首先尝试找到min而不是max)
#1
12
There's heapq.nlargest()
:
maxvalues = heapq.nlargest(20, lst)
From the doc:
从文档:
heapq.nlargest(n, iterable, key=None)
heapq.nlargest(n,iterable,key = None)
Return a list with the n largest elements from the dataset defined by
iterable
.key
, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable:key=str.lower
Equivalent to:sorted(iterable, key=key, reverse=True)[:n]
返回一个列表,其中包含iterable定义的数据集中的n个最大元素。 key(如果提供)指定一个参数的函数,该函数用于从iterable中的每个元素中提取比较键:key = str.lower等效于:sorted(iterable,key = key,reverse = True)[:n]
Or at the same way use heapq.nsmallest()
if you want the smallest.
或者以相同的方式使用heapq.nsmallest(),如果你想要最小的。
IMPORTANT NOTE from the doc:
来自doc的重要说明:
The latter two functions [
nlargest
andnsmallest
] perform best for smaller values ofn
. For larger values, it is more efficient to use thesorted()
function. Also, whenn==1
, it is more efficient to use the built-inmin()
andmax()
functions.后两个函数[nlargest和nsmallest]对较小的n值表现最佳。对于更大的值,使用sorted()函数更有效。此外,当n == 1时,使用内置的min()和max()函数效率更高。
#2
6
sorted(lst)[-20:]
is the shortest I can think of. Likely to be faster, too.
是我能想到的最短的。也可能更快。
(edited: first try found the min instead of the max)
(编辑:首先尝试找到min而不是max)