列表中最小的n个数字 [英] Smallest n numbers from a list
本文介绍了列表中最小的n个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个列表 list1 = [1,15,9,3,6,21,10,11]
如何从中获得最小的2个整数?
If I have a list list1=[1,15,9,3,6,21,10,11]
how do I obtain the smallest 2 integers from that?
min()
给我一个数字,但是2呢?
min()
gives me one number, but what about 2?
推荐答案
您可以导入 heapq
import heapq
list1=[1,15,9,3,6,21,10,11]
print(heapq.nsmallest(2,list1))
限制是,如果您有一个重复的值,例如 l = [1,3,5,1]
,则两个最小值将是 [1,1]
.
The limitation with that is if you have a repeated value let's say l=[1,3,5,1]
, the two smallest values will be [1,1]
.
In [2]:
list1=[1,15,9,3,6,21,10,11]
In [3]:
%timeit sorted(list1)[:2]
1000000 loops, best of 3: 1.58 µs per loop
In [5]:
import heapq
%timeit heapq.nsmallest(2,list1)
100000 loops, best of 3: 4.18 µs per loop
从这两者看来,对较小的集合排序列表似乎更快.
From the two, it seems sorting the list is faster for smaller sets.
In [14]:
import random
list1=[[random.random() for i in range(100)] for j in range(100)]
In [15]:
%timeit sorted(list1)[:2]
10000 loops, best of 3: 55.6 µs per loop
In [16]:
import heapq
%timeit heapq.nsmallest(2,list1)
10000 loops, best of 3: 27.7 µs per loop
感谢Padraic Cunningham, heapq
在设置较大的集合时更快
Thanks to Padraic Cunningham, heapq
is faster with larger sets
这篇关于列表中最小的n个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文