This article mainly introduced the Python queue definition and use method, combined with the concrete instance form analysis Python definition and the use queue's concrete operation skill and the attention matter, needs the friend can refer to the next
The examples in this article describe the definition and use of Python queues. Share to everyone for your reference, as follows:
Although Python has its own queue module, we only need to introduce the module when it is used, but in order to better understand the queue, we will implement the queue.
Queue is a data structure, it is characterized by first-out, that is, the end of the team to add an element, the team head to remove an element, similar to the shopping malls queued checkout, the first person to take the account, and then the end of the queue. In our daily life, sending text messages will be used in the queue. Here is the code for the Python implementation queue:
#!/usr/bin/python#coding=utf-8class Queue (object): Def init (self, size): self.size = size Self.queue = [] def St R (Self): return str (self.queue) #获取队列的当前长度 def getsize (self): return len (self.quene) #入队, if the queue is full returns 1 or throws an exception, Otherwise, insert the element into the queue end Def enqueue (self, items): if Self.isfull (): return-1 #raise Exception ("queue was full") Self.queue.append (items) #出队, if the queue returns 1 or throws an exception, return the queue header element and remove the Def dequeue (self) from the queue: if Self.isempty Return-1 #raise Exception ("Queue is Empty") firstelement = self.queue[0] self.queue.remove ( firstelement) return firstelement #判断队列满 def isfull (self): if Len (self.queue) = = Self.size: return True return False #判断队列空 def isempty (self): if Len (self.queue) = = 0: return True return False
The following is the test code for the queue class. py File:
If name = = ' main ': Queuetest = Queue (Ten) for I in range: queuetest.enqueue (i) print queuetest.isfull () print que Uetest print queuetest.getsize () for I in range (5): Print queuetest.dequeue () print queuetest.isempty () print Queuete St Print Queuetest.getsize ()
Test results: