TOPk实现(python)
阅读原文时间:2023年08月15日阅读:3

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()