博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python collections deque - double-ended queue ()
阅读量:4030 次
发布时间:2019-05-24

本文共 6017 字,大约阅读时间需要 20 分钟。

8.3.2.  objects

class 
collections.
deque
(
[
iterable
[
maxlen
]
]
)

Returns a new deque object initialized left-to-right (using ) with data from iterable. If iterable is not specified, the new deque is empty.

Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

Though  objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

New in version 2.4.

If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.

Changed in version 2.6: Added maxlen parameter.

Deque objects support the following methods:

append
(
x
)

Add x to the right side of the deque.

appendleft
(
x
)

Add x to the left side of the deque.

clear
(
)

Remove all elements from the deque leaving it with length 0.

count
(
x
)

Count the number of deque elements equal to x.

New in version 2.7.

extend
(
iterable
)

Extend the right side of the deque by appending elements from the iterable argument.

extendleft
(
iterable
)

Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument.

pop
(
)

Remove and return an element from the right side of the deque. If no elements are present, raises an .

popleft
(
)

Remove and return an element from the left side of the deque. If no elements are present, raises an .

remove
(
value
)

Removed the first occurrence of value. If not found, raises a .

New in version 2.5.

reverse
(
)

Reverse the elements of the deque in-place and then return None.

New in version 2.7.

rotate
(
n
)

Rotate the deque n steps to the right. If n is negative, rotate to the left. Rotating one step to the right is equivalent to: d.appendleft(d.pop()).

Deque objects also provide one read-only attribute:

maxlen

Maximum size of a deque or None if unbounded.

New in version 2.7.

In addition to the above, deques support iteration, pickling, len(d)reversed(d)copy.copy(d)copy.deepcopy(d), membership testing with the  operator, and subscript references such as d[-1]. Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead.

Example:

>>>
>>> from collections import deque>>> d = deque('ghi')                 # make a new deque with three items>>> for elem in d:                   # iterate over the deque's elements...     print elem.upper()GHI>>> d.append('j')                    # add a new entry to the right side>>> d.appendleft('f')                # add a new entry to the left side>>> d                                # show the representation of the dequedeque(['f', 'g', 'h', 'i', 'j'])>>> d.pop()                          # return and remove the rightmost item'j'>>> d.popleft()                      # return and remove the leftmost item'f'>>> list(d)                          # list the contents of the deque['g', 'h', 'i']>>> d[0]                             # peek at leftmost item'g'>>> d[-1]                            # peek at rightmost item'i'>>> list(reversed(d))                # list the contents of a deque in reverse['i', 'h', 'g']>>> 'h' in d                         # search the dequeTrue>>> d.extend('jkl')                  # add multiple elements at once>>> ddeque(['g', 'h', 'i', 'j', 'k', 'l'])>>> d.rotate(1)                      # right rotation>>> ddeque(['l', 'g', 'h', 'i', 'j', 'k'])>>> d.rotate(-1)                     # left rotation>>> ddeque(['g', 'h', 'i', 'j', 'k', 'l'])>>> deque(reversed(d))               # make a new deque in reverse orderdeque(['l', 'k', 'j', 'i', 'h', 'g'])>>> d.clear()                        # empty the deque>>> d.pop()                          # cannot pop from an empty dequeTraceback (most recent call last):  File "
", line 1, in -toplevel- d.pop()IndexError: pop from an empty deque>>> d.extendleft('abc') # extendleft() reverses the input order>>> ddeque(['c', 'b', 'a'])

8.3.2.1.  Recipes

This section shows various approaches to working with deques.

Bounded length deques provide functionality similar to the tail filter in Unix:

def tail(filename, n=10):    'Return the last n lines of a file'    return deque(open(filename), n)

Another approach to using deques is to maintain a sequence of recently added elements by appending to the right and popping to the left:

def moving_average(iterable, n=3):    # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0    # http://en.wikipedia.org/wiki/Moving_average    it = iter(iterable)    d = deque(itertools.islice(it, n-1))    d.appendleft(0)    s = sum(d)    for elem in it:        s += elem - d.popleft()        d.append(elem)        yield s / float(n)

The rotate() method provides a way to implement  slicing and deletion. For example, a pure Python implementation of del d[n] relies on the rotate() method to position elements to be popped:

def delete_nth(d, n):    d.rotate(-n)    d.popleft()    d.rotate(n)

To implement  slicing, use a similar approach applying rotate() to bring a target element to the left side of the deque. Remove old entries with popleft(), add new entries with extend(), and then reverse the rotation. With minor variations on that approach, it is easy to implement Forth style stack manipulations such as dupdropswapoverpick,rot, and roll.

转载地址:http://iohbi.baihongyu.com/

你可能感兴趣的文章
[关注大学生]李开复给中国计算机系大学生的7点建议
查看>>
[关注大学生]大学毕业生择业:是当"鸡头"还是"凤尾"?
查看>>
[茶余饭后]10大毕业生必听得歌曲
查看>>
gdb调试命令的三种调试方式和简单命令介绍
查看>>
C++程序员的几种境界
查看>>
VC++ MFC SQL ADO数据库访问技术使用的基本步骤及方法
查看>>
VUE-Vue.js之$refs,父组件访问、修改子组件中 的数据
查看>>
Vue-子组件改变父级组件的信息
查看>>
Python自动化之pytest常用插件
查看>>
Python自动化之pytest框架使用详解
查看>>
【正则表达式】以个人的理解帮助大家认识正则表达式
查看>>
性能调优之iostat命令详解
查看>>
性能调优之iftop命令详解
查看>>
非关系型数据库(nosql)介绍
查看>>
移动端自动化测试-Windows-Android-Appium环境搭建
查看>>
Xpath使用方法
查看>>
移动端自动化测试-Mac-IOS-Appium环境搭建
查看>>
Selenium之前世今生
查看>>
Selenium-WebDriverApi接口详解
查看>>
Selenium-ActionChains Api接口详解
查看>>