繁体   English   中英

如何将项目放在python中的队列顶部?

[英]How to put item on top of the Queue in python?

是否可以将项目放在队列的顶部而不是底部? 在相同的情况下,我需要在获得项目之后通过维护原始订单来重新填充队列。

不,根据定义,放入队列就是结束。

您想改用双端队列

DeepSpace 的建议之后,这里有一个简单的实现,将一个项目放在 python 队列的前面(顶部),使用: appendleft()

from collections import deque

Q=deque([2,1,5,7,4,3])
Q.appendleft(8)
print('{}{}'.format("head: ", Q[0]))

出:

deque([8, 2, 1, 5, 7, 4, 3])
head: 8

如果您反对使用appendleft()您可以使用列表属性并执行以下操作:

deque([8]+list(Q))

deque([8, 2, 1, 5, 7, 4, 3])

唯一的问题是dequeue不会等待.pop()上的新消息。

您需要扩展队列类才能这样做。

import queue

class UngetQueue(queue.Queue):
    def unget(self, item, block=True, timeout=None):
        '''Put an item into the head of the queue.
        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until a free slot is available. If 'timeout' is
        a non-negative number, it blocks at most 'timeout' seconds and raises
        the Full exception if no free slot was available within that time.
        Otherwise ('block' is false), put an item on the queue if a free slot
        is immediately available, else raise the Full exception ('timeout'
        is ignored in that case).
        '''
        with self.not_full:
            if self.maxsize > 0:
                if not block:
                    if self._qsize() >= self.maxsize:
                        raise Full
                elif timeout is None:
                    while self._qsize() >= self.maxsize:
                        self.not_full.wait()
                elif timeout < 0:
                    raise ValueError("'timeout' must be a non-negative number")
                else:
                    endtime = time() + timeout
                    while self._qsize() >= self.maxsize:
                        remaining = endtime - time()
                        if remaining <= 0.0:
                            raise Full
                        self.not_full.wait(remaining)
            self._unget(item)
            self.unfinished_tasks += 1
            self.not_empty.notify()

    def _unget(self, item):
        self.queue.appendleft(item)

这对我有用:

from queue import Queue
q = Queue()
element = 1
q.put(2)
q.put(3)
q.queue.insert(0, element) # Insert element in index 0 (begin).
while not q.empty():
     print(q.get())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM