我想要跟踪前N个最大值,给定传入数据点的流(可能非常大)。N是一个相对较小的数字,比方说在10的附近,而不是数百或更多。下面的代码是高效的,还是有更好的方法呢?
import heapq
n = 10
topn = []
def push(item):
global topn
if len(topn) >= n:
heapq.heappushpop(topn, item)
else:
heapq.push(topn, item)发布于 2016-03-05 16:29:56
heapq.nlargest()的实现方式如下:
def nlargest(n, iterable):
"""Find the n largest elements in a dataset.
Equivalent to: sorted(iterable, reverse=True)[:n]
"""
if n < 0:
return []
it = iter(iterable)
result = list(islice(it, n))
if not result:
return result
heapify(result)
_heappushpop = heappushpop
for elem in it:
_heappushpop(result, elem)
result.sort(reverse=True)
return resulthttps://stackoverflow.com/questions/35804586
复制相似问题