python - 如何打印队列前面的元素python 3?

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


    import queue
    q = queue.Queue()
    q.put(5)
    q.put(7)

print(q.get()) 删除队列前面的元素。如何打印这个元素而不删除它?可以这样做吗?

最佳答案

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
>>>

关于python - 如何打印队列前面的元素python 3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53234946/

相关文章:

unicode - smtplib 在 Python 3.1 中使用 unicode 字符发送邮件的问题

regex - 'if' 语句中的 Perl 正则表达式 [语法]

c++ - 嵌套 C++ 模板中的引用类型

python - 自动放置注释气泡

python3 : having problems with os. 步行

syntax - Go 语法和接口(interface)作为函数的参数

使用 vertica-python 将 Python pandas 数据帧转换为 vertica 表

python - gensim - Word2vec 继续训练现有模型 - AttributeError : 'Word2Vec' object has no attribute 'compute_loss'

python - 是否有内置函数(或其他方法)在元素 <= 限制时迭代列表?

python - 如何在 Django 中基于另一个模型的实例创建模型,但经过过滤