检查 python 队列中的项目 [英] examining items in a python Queue

查看:68
本文介绍了检查 python 队列中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不调用 .get() 的情况下在 Python 中检查 Queue 中的项目?根据文档,队列中不允许索引.我需要检查队列头部的项目是否满足某些条件,如果满足,则将其从队列中删除.同样,我需要检查队列中的任何其他项目是否满足类似条件并将其删除.

Is it possible to examine items in a Queue in Python without calling .get()? As per the docs, indexing is not allowed in Queue. I need to check if the item at the head of the queue satisfies some condition and if it does, remove it from the queue. Similarly I need to check if any other item in the queue satisfy the similar condition and remove it.

我在这里使用了错误的数据结构吗?

Am I using the wrong data structure here?

推荐答案

Queue 模块实现了多生产者、多消费者队列.当信息必须在多个线程之间安全交换时,它在线程编程中特别有用.

The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads.

如您所见,Queue 模块是专为与线程一起使用而创建的,仅提供FIFOLIFO优先级队列,没有一个提供这个功能.但是,通过检查 Queue<的源代码/code> 模块,你可以看到它只是使用了一个 collections.deque(双端队列)可以轻松完成你的任务.您可以在恒定时间内索引第一项 ([0]) 和 .popleft().

As you can see, the Queue module was created specifically for use with threads, providing only FIFO, LIFO and priority queues, none of which provide this functionality. However by examining the source code of the Queue module, you can see that it simply uses a collections.deque (double ended queue) which can easily accomplish your task. You may index the first item ([0]) and .popleft() in constant time.

这篇关于检查 python 队列中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆