是否可以将项目放在队列的顶部而不是底部? 在同样的情况下,我需要通过保留原始订单来重新填充队列,之后我就会收到物品。
答案 0 :(得分:4)
不,根据定义,最终会进入队列。
您想改用deque。
答案 1 :(得分:0)
根据 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))
答案 2 :(得分:0)
唯一的问题是dequeue
不等待新消息出现在.pop()
上。推送
答案 3 :(得分:0)
您需要扩展队列类。
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)