TOPk实现(python)
Posted muzinan110
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TOPk实现(python)相关的知识,希望对你有一定的参考价值。
import heapq class TopK: def __init__(self, iterable, k): self.minheap = [] self.capacity = k self.iterable = iterable def push(self, val): if len(self.minheap) >= self.capacity: min_val = self.minheap[0] if val < min_val: pass else: heapq.heapreplace(self.minheap, val) else: heapq.heappush(self.minheap, val) def get_topk(self): for val in self.iterable: self.push(val) return self.minheap def test(): import random i = list(range(1000)) random.shuffle(i) _ = TopK(i, 10) print(_.get_topk()) if __name__ == ‘__main__‘: test()
以上是关于TOPk实现(python)的主要内容,如果未能解决你的问题,请参考以下文章