Queue in Python, deque

Source: Internet
Author: User
Tags shallow copy

Create a two-way queue

Import COLLECTIONSD = Collections.deque ()

Append (add an element to the right)

Import COLLECTIONSD = Collections.deque () d.append (1) d.append (2) print (d) #输出: Deque ([1, 2])

Appendleft (add an element to the left)

Import COLLECTIONSD = Collections.deque () d.append (1) d.appendleft (2) print (d) #输出: Deque ([2, 1])

Clear (Empty queue)

Import COLLECTIONSD = Collections.deque () d.append (1) d.clear () print (d) #输出: Deque ([])

Copy (shallow copy)

Import COLLECTIONSD = Collections.deque () d.append (1) new_d = D.copy () print (new_d) #输出: Deque ([1])

Count (returns the number of occurrences of the specified element)

Import COLLECTIONSD = Collections.deque () d.append (1) d.append (1) Print (D.count (1)) #输出: 2

Extend (extends the element of a list from the right side of the queue)

Import COLLECTIONSD = Collections.deque () d.append (1) d.extend ([3,4,5]) print (d) #输出: Deque ([1, 3, 4, 5])

Extendleft (extends the element of a list from the left side of the queue)

Import COLLECTIONSD = Collections.deque () d.append (1) d.extendleft ([3,4,5]) print (d) # # #输出: Deque ([5, 4, 3, 1])

Index (Find the index position of an element)

Import COLLECTIONSD = Collections.deque () d.extend ([' A ', ' B ', ' C ', ' d ', ' e ']) print (d) Print (D.index (' e ')) Print (D.index ( ' C ', 0,3))  #指定查找区间 # Output: deque ([' A ', ' B ', ' C ', ' d ', ' E ']) #     4#     2

Insert (Inserts an element at the specified location)

Import COLLECTIONSD = Collections.deque () d.extend ([' A ', ' B ', ' C ', ' d ', ' e ']) D.insert (2, ' Z ') print (d) #输出: deque ([' A ', ' B ') , ' Z ', ' C ', ' d ', ' e '])

Pop (Gets the rightmost element and deletes it in the queue)

Import COLLECTIONSD = Collections.deque () d.extend ([' A ', ' B ', ' C ', ' d ', ' e ']) x = D.pop () print (x,d) #输出: E deque ([' A ', ' B ', ' C ', ' d '])

Popleft (Gets the leftmost element and deletes it in the queue)

Import COLLECTIONSD = Collections.deque () d.extend ([' A ', ' B ', ' C ', ' d ', ' e ']) x = D.popleft () print (x,d) #输出: A deque ([' B ', ' C ', ' d ', ' e '])

Remove (removes the specified element)

Import COLLECTIONSD = Collections.deque () d.extend ([' A ', ' B ', ' C ', ' d ', ' e ']) d.remove (' C ') print (d) #输出: deque ([' A ', ' B ', ' d ', ' e '])

Reverse (queue reversal)

Import COLLECTIONSD = Collections.deque () d.extend ([' A ', ' B ', ' C ', ' d ', ' e ']) D.reverse () print (d) #输出: deque ([' E ', ' d ', ' C ' , ' B ', ' a '])

Rotate (Put the right element on the left)

Import COLLECTIONSD = Collections.deque () d.extend ([' A ', ' B ', ' C ', ' d ', ' e ']) d.rotate (2)   #指定次数, default 1 times print (d) # Output: Deque ([' d ', ' e ', ' A ', ' B ', ' C ')

The queue module introduces a module that implements 3 types of queues, the difference being in the order in which entries are retrieved in the queue. In FIFO queues, the entries are retrieved in first in, out order. In the LIFO queue, the last entry added is first retrieved (the operation is similar to a stack). In the priority queue, entries are saved as ordered (using the HEAPQ module) and the minimum entry is retrieved first. The queue module defines the following classes and exceptions: Class queue. The constructor for queue (maxsize=0) FIFO queues. MaxSize is an integer that represents the maximum number of entries in the queue. Once the queue is full, the insert will be blocked until there is free space in the queue. If MaxSize is less than or equal to 0, the queue size is unlimited. MaxSize defaults to 0
Import Queueimport timeq = queue. Queue () #FIFO队列先进先出q. Put (2) q.put (1) q.put (3) while not Q.empty ():    Next_item = Q.get ()    print (Next_item)    Time.sleep (1) Execution Result: 213
Class queue. Lifoqueue (Maxsize=0) The constructor for the LIFO queue. MaxSize is an integer that represents the maximum number of entries in the queue. Once the queue is full, the insert will be blocked until there is free space in the queue. If MaxSize is less than or equal to 0, the queue size is unlimited. MaxSize defaults to 0
Import Queueimport timeq = queue. Lifoqueue () #LIFO队列后进先出q. Put (2) q.put (1) q.put (3) while not Q.empty ():    Next_item = Q.get ()    print (Next_item)    time.sleep (1) Execution result: 312
Class queue. Priorityqueue (maxsize=0) priority queue, different from the normal queue first-in-first-out (although the literal or the queue, but in fact, regardless of the meaning or implementation, and the normal queue is very different), but also different from the stack of first-in and out. In the implementation, it generally through the heap of this data structure, and the heap is actually a complete binary tree, it will enter the elements of the container to sort (according to the pre-specified rules), the order of the team will be two fork tree root node represents the element.
From queue import Priorityqueueimport timeq = Priorityqueue () q.put ((2, ' Code ')) Q.put ((1, ' eat ')) Q.put ((3, ' sleep ')) While not Q.empty ():    Next_item = Q.get ()    print (Next_item)    time.sleep (3) Execution Result: (1, ' Eat ') (2, ' Code ') (3, ' Sleep ')
Exception queue. Empty when the queue is empty, the non-blocking get () or get_nowait () is called when the exception is thrown. Exception queue. When the queue is full, the non-blocking put () or put_nowait () is called, and the exception is thrown. The Queue object (queue, Lifoqueue, or Priorityqueue) provides the following methods: queue.qsize ()Returns the approximate size of the queue. Note that qsize () > 0 does not guarantee that the next get () method will not be blocked, nor does the Qsize () < maxsize guarantee that the put () is not blocked.
Import Queueimport timeq = queue. Queue () Q.put (2) q.put (1) q.put (3) q.put (' Python ') print (' Queue long:%s '%q.qsize ()) Execution Result: Queue Long:4

Queue.empty ()
Returns true if the queue is empty, otherwise false. If empty () returns True, there is no guarantee that the next put () call will not be blocked. Similarly, empty () returns false and does not guarantee that the next get () call will not be blocked.

Import Queueq = queue. Queue () que = queue. Queue () q.put (2) q.put (1) q.put (3) q.put (' Python ') print (' Q is empty?:%s '%q.empty ()) print (' Que are empty?:%s '%que.empty ( )) Execution Result: Q is empty? : False    #队列不为空则返回Falseque is empty?: True    #队列未空则返回True

Queue.full ()
Returns true if the queue is full, otherwise false. If full () returns True, there is no guarantee that the next get () call will not be blocked. Similarly, full () returns false and does not guarantee that the next put () call will not be blocked.

Import Queueq = queue. Queue (maxsize=4) que = queue. Queue () q.put (2) q.put (1) q.put (3) q.put (' Python ') print (' Q is full?:%s '%q.full ()) print (' Que are full?:%s '%que.full ()) Execution Result: Q is full? : Trueque is full? : False

Queue.put (item, block=true, Timeout=none)
Put the item into the queue. If block is True and timeout is None, the method waits until there is a queue with free space (default Block=true,timeout=none). If timeout is a positive integer, the method blocks up to timeout seconds and throws a full exception. If the block is false and the queue is full, it throws an outright exception (timeout is ignored).

Block is True

Import Queueimport timeq = queue. Queue (maxsize=2) #将q队列填满q. Put (' Python ') q.put (' Linux ') print (Time.ctime ())    #打印当前时间try:    #捕获queue. Full exception    #q. Put (' shell ', timeout=3)    #默认block =true      #q. Put (' Shell ', True, timeout=3)    #可以省略block = Directly write true;timeout= can omit the direct write 3    q.put (' Shell ', block=true, timeout=3)    #q队列已满, again put the data into Q, will block 3s after throwing an exception queue. Fullexcept queue. Full:    print (' queue is full! ')    Print (Time.ctime ())    #打印当前时间, which shows the Q queue blocking time execution result: Fri  3 15:06:43 2017queue is full! Fri Nov  3 15:06:46 2017

Block is False

Import Queueimport timeq = queue. Queue (maxsize=2) #将q队列填满q. Put (' Python ') q.put (' Linux ') print (Time.ctime ())    #打印当前时间try:    #捕获queue. Full exception    q.put (' Shell ', False, timeout=3)    #block为False时, timeout invalidation will immediately throw a queue. Full exception, so the timeout option can omit the except queue from being written. Full:    print (' queue is full! ')    Print (Time.ctime ())    #打印当前时间, you can see the Q queue blocking time execution results:

Queue.put_nowait (item)
Equivalent to put (item, False).

Queue.get (Block=true, Timeout=none)
The removal from the queue is returned with an entry. If block is True and timeout is None (default Block=true,timeout=none), the method will block until there are entries available in the queue. If timeout is a positive integer, the method will block a maximum of timeout seconds and throw an empty exception. If the block is false and the queue is empty, the empty exception is thrown directly (at which time timeout is ignored).

Block is True

Import Queueimport timeq = queue. Queue (maxsize=2) #当前q队列填为空print (Time.ctime ())    #打印当前时间try:    #捕获queue. Empty exception    Q.get (True, 5)    #Queue. Get () gets data blocking 5sexcept Queue. Empty:    print (' queue is empty! ')    Print (Time.ctime ())    #打印当前时间, you can see the Q queue blocking time execution results:

Block is False

Import Queueimport timeq = queue. Queue (maxsize=2) #当前q队列填为空print (Time.ctime ())    #打印当前时间try:    #捕获queue. Empty exception    #q. Get (False, 5)    #Queue. Get () Get data block 5s,block=/timeout= can be omitted; block=false timeout can omit    q.get ( False) except queue. Empty:    print (' queue is empty! ')    Print (Time.ctime ())    #打印当前时间, which shows the Q queue blocking time execution result: Fri  3 15:38:23 2017queue is empty! Fri Nov  3 15:38:23 2017

Queue.get_nowait ()
Equivalent to get (False).

Queue.task_done ()
Represents the completion of a task in a previous queue. Used by queue consumer threads. For each get () get to the task, the next call to Task_done () tells the queue that the processing of the task has been completed.
If a join () call is blocking, when all entries in the queue are processed it resumes execution (meaning that the task_done () call is received by each entry in the queue).
A ValueError exception is thrown if the number of calls exceeds the amount of entries placed in the queue.

Queue.join ()Blocks until all entries in the queue are fetched and processed.
When an entry is added to the queue, the count of unfinished tasks increases. When a consumer thread calls Task_done (), the count of unfinished tasks is reduced. When the count of unfinished tasks is reduced to 0 o'clock, join () unlocks.
 #!/usr/bin/env python3import queueimport timeimport subprocessimport threadingq = queue. Queue () hosts = [' 192.168.1.68 ', ' 192.168.1.118 ', ' 192.168.1.101 ', ' 192.168.1.250 ', ' 192.168.1.133 ']def run (): While Tru E: The #防止线程少于len (hosts) when the card is dead, do not have a while loop thread count will cause the queue data can not be fully completed, will cause Queue.join () blocked state host = Q.get () if host = = ' 19        2.168.1.118 ': #如果ip等于192.168.1.118 is dormant 10S, used to interpret queue.join () blocking until Queue.task_doen () notification after contact blocking Time.sleep (10) Print (' Host IP is:%s '% host) Q.task_done () #当前线程任务完成def main (): For I in range: T = Threading. Thread (Target=run) T.setdaemon (True) T.start () for item in Hosts:q.put (item) q.join () #阻塞直至 All Threads Queue.task_done () return start = Time.time () main () print ("Elapsed time:%s"% (Time.time ()-start)) Execution result: host IP is:192.168 .88.68host IP is:192.168.68.101host IP is:192.168.66.250host IP is:192.168.88.133host IP is:192.168.88.118elapsed time: 10.013836145401001 #由于192.168.1.118 approximately blocked 10S 

Queue in Python, deque

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.