Python Data Structure 简明教程
Python - Queue
我们在日常生活中熟悉队列,因为它是一种等待服务的排队方式。队列数据结构也意味着同样的情况,其中数据元素按队列排列。队列的独特性在于添加和删除项目的方式。项目在一边允许,但在另一边删除。所以它是一种先进先出方法。
We are familiar with queue in our day to day life as we wait for a service. The queue data structure aslo means the same where the data elements are arranged in a queue. The uniqueness of queue lies in the way items are added and removed. The items are allowed at on end but removed form the other end. So it is a First-in-First out method.
可以使用 python 列表实现队列,其中我们可以使用 insert() 和 pop() 方法来添加和删除元素。没有插入,因为数据元素总是添加到队列的末尾。
A queue can be implemented using python list where we can use the insert() and pop() methods to add and remove elements. Their is no insertion as data elements are always added at the end of the queue.
Adding Elements
在下面的示例中,我们创建一个队列类,在其中实施了先进先出方法。我们使用内置的 insert 方法添加数据元素。
In the below example we create a queue class where we implement the First-in-First-Out method. We use the in-built insert method for adding data elements.
Example
class Queue:
def __init__(self):
self.queue = list()
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
def size(self):
return len(self.queue)
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.size())
Removing Element
在下例中,我们创建一个队列类,其中我们插入数据,然后使用内置的弹出方法删除数据。
In the below example we create a queue class where we insert the data and then remove the data using the in-built pop method.
Example
class Queue:
def __init__(self):
self.queue = list()
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
# Pop method to remove element
def removefromq(self):
if len(self.queue)>0:
return self.queue.pop()
return ("No elements in Queue!")
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.removefromq())
print(TheQueue.removefromq())