How to put items into priority queues?

后端 未结 3 1162
無奈伤痛
無奈伤痛 2020-12-23 16:57

In the Python docs,

The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]

3条回答
  •  失恋的感觉
    2020-12-23 17:24

    I made something like this to accomplish a FIFO similar to gfortune, but without the need of calling time.time() everywhere: (Python 3 only)

    import time
    from dataclasses import dataclass, field
    
    @dataclass(order=True)
    class PrioritizedItem:
        prio: int
        timestamp: float = field(init=False, default_factory=time.time)
        data: object = field(compare=False)
    

    Now you can do:

    import queue
    
    item1 = PrioritizedItem(0, "hello world")
    item2 = PrioritizedItem(0, "what ever")
    q = queue.PriorityQueue()
    q.put(item1)
    q.put(item2)
    

    And be sure, they will always be extracted in the same order.

提交回复
热议问题