How to make heapq evaluate the heap off of a specific attribute?

后端 未结 7 734
野的像风
野的像风 2020-11-30 22:07

I wish to hold a heap of objects, not just numbers. They will have an integer attribute in them that the heap can sort by. The easiest way to use heaps in python is heapq,

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 22:50

    You could implement a heapdict. Note the use of popitem() to get the lowest priority item.

    import heapdict as hd
    import string
    import numpy as np
    
    h = hd.heapdict()
    keys = [char for char in string.ascii_lowercase[:10]]
    vals = [i for i in np.random.randint(0,10, 10)]
    for k,v in zip(keys,vals):
        h[k] = v
    for i in range(len(vals)):
        print h.popitem()
    

提交回复
热议问题