Deque dual-end queue structure in the collections module of Python

Source: Internet
Author: User
The deque structure can be viewed as an enhanced version of the built-in list structure and provides more powerful methods than queues. The following describes the deque dual-end queue structure in the collections module of Python through several small examples: deque is the abbreviation of double-ended queue. it is similar to list, but it provides insert and delete operations on both ends.

  • Appendleft is inserted on the left of the list.
  • Value on the left of the popleft pop-up list
  • Extendleft extension on the left

For example:

queue = deque()# append values to wait for processingqueue.appendleft("first")queue.appendleft("second")queue.appendleft("third")# pop values when readyprocess(queue.pop()) # would process "first"# add values while processingqueue.appendleft("fourth")# what does the queue look like now?queue # deque(['fourth', 'third', 'second'])

As a dual-end queue, deque also provides some other useful methods, such as rotate. let's take a look at the following:

Fill
Deque can be filled from any end. in python implementation, it is called "left end" and "right end ".

import collectionsd1 = collections.deque()d1.extend('abcdefg')print 'extend:', d1d1.append('h')print 'append:', d1d2 = collections.deque()d2.extendleft(xrange(6))print 'extendleft', d2d2.appendleft(6)print 'appendleft', d2

Extendleft () iterates over its input, and processes each element the same as appendleft.

extend: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])append: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])extendleft deque([5, 4, 3, 2, 1, 0])appendleft deque([6, 5, 4, 3, 2, 1, 0])

Exploitation
The deque element can be used from both ends, depending on the applied algorithm.

import collectionsprint "From the right:"d = collections.deque('abcdefg')while True: try:  print d.pop(), except IndexError:  breakprintprint "\nFrom the left:"d = collections.deque(xrange(6))while True: try:  print d.popleft(), except IndexError:  breakprint

You can use pop () to delete an element from the right side of deque, and use popleft () to delete an element from the left side of deque.

From the right:g f e d c b aFrom the left:0 1 2 3 4 5

Because the dual-end queue is thread-safe, the queue content can be used from both ends in different threads at the same time.

import collectionsimport threadingimport timecandle = collections.deque(xrange(5))def burn(direction, nextSource): while True:  try:   next = nextSource()  except IndexError:   break  else:   print '%8s: %s' % (direction, next)   time.sleep(0.1) print '%8s done' % direction returnleft = threading.Thread(target=burn, args=('Left', candle.popleft))right = threading.Thread(target=burn, args=('Right', candle.pop))left.start()right.start()left.join()right.join()

The thread processes the two ends alternately and deletes the element. the deque is empty.

 Left: 0 Right: 4 Right: 3 Left: 1 Right: 2 Left done Right done

Rotate
Another role of deque can be rotated in any direction, and some elements can be skipped.

import collectionsd = collections.deque(xrange(10))print 'Normal:', dd= collections.deque(xrange(10))d.rotate(2)print 'Right roration:', dd = collections.deque(xrange(10))d.rotate(-2)print 'Left roration:', d

Result:

Normal: deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])Right roration: deque([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])Left roration: deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])

Another example:

#-*-Coding: UTF-8-*-"The following is an interesting example, the deque rotate method is used to implement an infinite loop loading animation "import sysimport timefrom collections import dequefancy_loading = deque ('> ------------------') while True: print '\ r % s' % ''. join (fancy_loading), fancy_loading.rotate (1) sys. stdout. flush () time. sleep (0.08)

Output result:

# An endless loop drive lamp -------------> -------

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.