Python队列

时间:2020-02-23 14:43:11  来源:igfitidea点击:

在之前的教程中,我们讨论了有关time模块的python time sleep函数。
在本教程中,我们将学习python队列模块。

Python队列

当我们要以到达的方式处理数据时,最好使用队列。
队列是先进先出数据结构的概念。
看下面的例子:

# importing the queue module
import queue

# taking an object of Queue()
q = queue.Queue()

# enqueueing some value in the object of Queue
q.put('A')
q.put('B')
q.put('C')
q.put('D')
q.put('E')

# retrieving the values of the Queue
for i in range(q.qsize()):
 print(q.get())

这将输出:

Python队列示例代码分析

在第一行中,我们导入了python队列模块。
然后,我们创建了一个Queue对象,因为该队列模块包含三个类,例如Queue,LifoQueue和PriorityQueue。

然后,我们使用put()方法向队列对象添加了一些值。
最后,我们使用get()方法检索了直到q大小的值。
而且,如果您注意到输出,您将看到输出与我们添加的方式相同。

Python Queue常用方法

在python队列模块中,以下是用于操作队列对象或者对其进行操作的最常用方法。
在前面的示例中,我们已经看到了三种方法。
它们是put(),get()和qsize()。
我们将看到其他一些方法。

Python队列full()函数

检查队列对象是否已满。
如果队列已满,则返回true,否则返回false。

Python Queue empty()函数

如果队列为空,则返回true,否则返回false。

请参见以下示例:

# importing only the Queue from the queue module
from queue import Queue

# taking an object of Queue()
q = Queue()
print("Initially the size of queue is %s" % q.qsize())
print("Checking whether queue is empty or not. Empty?? = %s" % q.empty())

# enqueueing some value in the object of Queue
q.put('A')
q.put('B')
q.put('C')
q.put('D')
q.put('E')

print("After adding some value, size of queue is %s" % q.qsize())
print("Checking whether queue is full or not. Full?? = %s" % q.full())

# retrieving the values of the Queue
for i in range(q.qsize()):
 print("Retrieved = ", end=' ')
 print(q.get())

# after retrieving, check the size of the object
print("Size of queue is = %s " % q.qsize())

上面的python队列示例代码将产生以下输出。

Initially the size of queue is 0
Checking whether queue is empty or not. Empty?? = True
After adding some value, size of queue is 5
Checking whether queue is full or not. Full?? = False
Retrieved =  A
Retrieved =  B
Retrieved =  C
Retrieved =  D
Retrieved =  E
Size of queue is = 0

Python LifoQueue

Python LifeQueue与队列相似,除了它的后进先出数据结构。
以下是一个简单的python LifoQueue示例代码。

import queue

q = queue.LifoQueue()

q.put('A')
q.put('B')
q.put('C')

for i in range(q.qsize()):
  print(q.get())

下图显示了python LifoQueue示例代码产生的输出。

Python优先级队列

Priority Queue按优先级顺序返回项目。
因此,当我们将一个项目添加到优先级队列时,我们也会提供它的优先级。
然后我们检索项目,它们按优先级顺序返回。
优先级较低的项目将首先返回。

以下是python PriorityQueue示例代码。

import queue

q = queue.PriorityQueue()

q.put((1, 'A'))
q.put((3, 'B'))
q.put((2, 'C'))

for i in range(q.qsize()):
  print(q.get())

这是python优先级队列示例程序产生的输出。

优先级队列Python heapq模块

Python Queue模块的" PriorityQueue"功能已同步。
还有另一个模块" heapq",也可以在python中实现优先级队列。

import heapq

q = []

heapq.heappush(q, (2, 'B'))
heapq.heappush(q, (1, 'A'))
heapq.heappush(q, (3, 'C'))

while q:
  item = heapq.heappop(q)
  print(item)