找到最大的N个元素(列表,字典)

方法1,通过heapq的nlargest()
方法2,通过heapq的堆,每次找到一个最大或最小的元素

测试:10000个随机数,两种对比,如果N较小还是堆快

import random
import heapq
import datetime

l = []
for i in range(1,10000):
    l.append(random.randint(1, 10000))

t1 = datetime.datetime.now()
nums = heapq.nlargest(3,l)
t2 = datetime.datetime.now()
print('method 1, time: %d' % (t1-t2).microseconds)
print(nums)

t1 = datetime.datetime.now()
heap = list(l)
heapq.heapify(heap)
heapq.heappop(heap)
heapq.heappop(heap)
heapq.heappop(heap)
t2 = datetime.datetime.now()
print('method 2, time: %d' % (t1-t2).microseconds)

mengan$ python topk.py 
method 1, time: 998607
[9998, 9998, 9997]
method 2, time: 994779

你可能感兴趣的:(找到最大的N个元素(列表,字典))