如何打印队列前面的元素 python 3?
how to print the element at front of a queue python 3?
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
>>>
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
>>>