You can import heapq
import heapq
list1=[1,15,9,3,6,21,10,11]
print(heapq.nsmallest(2,list1))
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]
.
Edit 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.
Edit 2:
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
Thanks to Padraic Cunningham, heapq
is faster with larger sets
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…