【问题标题】:how to print the element at front of a queue python 3? [duplicate]如何在队列python 3前面打印元素? [复制]
【发布时间】:2018-11-10 00:29:14
【问题描述】:
导入队列 q = queue.Queue() q.put(5) q.put(7)

print(q.get()) 删除队列前面的元素。如何在不删除它的情况下打印此元素?有可能吗?

【问题讨论】:

  • 如果你不使用队列作为线程间通信机制,你应该使用collections.deque,而不是queue.Queue。如果您使用队列在线程之间进行通信,那么 peek 操作对于此类用例很少有用或安全,您应该仔细考虑是否需要它。

标签: python python-3.x syntax queue python-collections


【解决方案1】:

Queue 对象有一个 collections.deque 对象属性。请参阅有关效率方面访问双端队列元素的 Python 文档。如果您需要随机访问元素,列表可能是更好的用例。

import queue

if __name__ == "__main__":
    q = queue.Queue()
    q.put(5)
    q.put(7)

    """
    dir() is helpful if you don't want to read the documentation
    and just want a quick reminder of what attributes are in your object
    It shows us there is an attribute named queue in the Queue class
    """
    for attr in dir(q):
        print(attr)

    #Print first element in queue
    print("\nLooking at the first element")
    print(q.queue[0])

    print("\nGetting the first element")
    print(q.get())

    print("\nLooking again at the first element")
    print(q.queue[0])

注意:我已经缩写了 dir 迭代器的输出

>>>
put
put_nowait
qsize
queue
task_done
unfinished_tasks

Looking at the first element
5

Getting the first element
5

Looking again at the first element
7
>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2017-12-23
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多