【问题标题】:How to find the most recently added item to a Queue in python?如何在python中找到最近添加到队列的项目?
【发布时间】:2012-09-30 09:47:22
【问题描述】:

我想知道最近排队的项目在队列中是什么。我怎么知道这个?

换句话说,如何找到队列将出队的最后一个项目(或最近入队的项目)

【问题讨论】:

    标签: python


    【解决方案1】:

    你是如何实现你的队列的?如果它被实现为一个列表,那么yourdata.pop(0) 可能会删除并返回第一项。最近入队的项目将位于列表的末尾,yourdata.pop() 删除并返回,或 yourdata[-1] 查看项目而不修改列表内容。

    对队列使用列表是个坏主意,因为会降低性能,但是:每次删除第一个项目时,都必须更新列表中的所有后续项目。您将从collections.deque 等专门的队列实现中获得更好的性能。见讨论: http://docs.python.org/tutorial/datastructures.html#using-lists-as-queues

    有关 python 中 Queue 与 deque 的信息,请参阅: Queue.Queue vs. collections.deque

    【讨论】:

      【解决方案2】:

      我不完全确定您要在这里实现什么,但以下可能有效,只需检查队列是否为空。

      >>> from Queue import Queue
      >>> q = Queue()    
      >>> _ = [q.put(index) for index in xrange(2, 10)]
      >>> if not q.empty():
      ...    q.queue[-1]
      9
      >>> 
      

      我假设您使用的是 python 自己的 Queue 对象,我会推荐它,因为它是线程安全的:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-11
        • 2021-03-30
        • 1970-01-01
        • 2022-12-23
        • 2019-03-25
        • 2015-08-23
        • 2018-09-18
        相关资源
        最近更新 更多