2 回答
TA贡献1864条经验 获得超6个赞
您可以使用该heapq模块。
只要您不使用多线程,它就可以完成您想做的事情,并且可能比其他优先级队列要快。
heap = [] # creates an empty heap
heappush(heap, item) # pushes a new item on the heap
item = heappop(heap) # pops the smallest item from the heap
item = heap[0] # smallest item on the heap without popping it
heapify(x) # transforms list into a heap, in-place, in linear time
这是一个例子:
>>> from heapq import *
>>> l = []
>>> heappush(l, (4, 'element')) # priority, element
>>> l
[(4, 'element')]
>>> heappush(l, (3, 'element2'))
>>> l
[(3, 'element2'), (4, 'element')]
>>> heappush(l, (5, 'element3'))
>>> l
[(3, 'element2'), (4, 'element'), (5, 'element3')]
>>> heappop(l)
(3, 'element2')
>>> heappop(l)
(4, 'element')
>>> heappop(l)
(5, 'element3')
len(l) 可用于确定内部元素的数量。
当l只有整数时,您提到的循环应如下所示:
l = [(3, 1000), (4, 2000), (5, 500)]
estimated = sum(t[1] for t in l)
totalSize = sum(t[0] for t in l)
备择方案
如果您的优先级较少且元素众多,那么存储桶将是不错的选择。 {priority : [queue]}
TA贡献1815条经验 获得超10个赞
while k < self.numItems:
estimated += self.items[k].value
totalSize += self.items[k].weight
k += 1
==
estimated = sum(item.value for item in self.items)
totalSize = sum(item.weight for item in self.items)
添加回答
举报