collections deque(双向队列)

来源:互联网 发布:mac os x是什么 编辑:程序博客网 时间:2024/06/05 16:26

class collections.deque([iterable[, maxlen]])
通过迭代iterable中的数据返回一个从左至右初初始化的deques对象。

>>> d = deque('abcdef')>>> ddeque(['a', 'b', 'c', 'd', 'e', 'f'])

如果没有指定iterable,返回一个新的空的deque对象

>>> deque()deque([])

双向队列是stacks栈 和 queues的概括(deque是“double-ended queue”的简写)。Deque支持线程安全的,高效的从双向队列的两端添加,删除数据(时间复杂度为O(1))
尽管list对象支持想似的操作,但列表只优化了快速的固定长度的操作。像pop(0)insert(0, v)这样改变列表长度和元素展示位置的操作会带来O(n)的内存移动消耗。
如果maxlen没有指定,或为None,deque可以增长到任意长度。然而,deque可以绑定指定最大长度值。如果被绑定的deque满了,当新元素被添加,相应数量的元素将从deque相反的一端消失。绑定长度的deque提供的功能和Unixtail过滤器命令相似。双向队列对于跟踪交易和在一堆数据中发现只有最近活跃的数据很有用

双向队列提供以下的方法:
append(x)
在双向队列的右边追加x

appendleft(x)
在双向队列的左边追加x

clear()
从双向队列中删除所有的元素

count(x)
计算x在双向队列中出现的次数

extend(iterable)
拓展双向队列的右侧通过迭代iterable中的每个元素,依次追加在右侧

extendleft(iterable)
拓展双向队列的左侧通过迭代iterable中的每个元素,依次追回在左侧

pop()
从双向队列的右侧删除并返回一个元素,如果双向队列目前没有元素,会引发一个IndexError

popleft()
从双向队列的左侧删除并返回一个元素,如果双向队列目前没有元素,会引发一个IndexError

remove(value)
删除从左边发现的第一value。如果没有找到,引发一个ValueError

reverse()
反转双向队列的元素,返回None

rotate(n)
向右侧旋转n个步长。如果n是负数,向左侧旋转。向右侧旋转一个步长相当于d.appendleft(d.pop)

双向队列也提供一个只读属性:
maxlen
双向队列能内容的最大值,如果没有绑定则返回None

除了一面提到的,双向队列也支持迭代,序列化,len(d), reversed(d),copy.copy(d),copy,deepcopy(d),成员关系检测in,下标引用例如d[-1]。通过下标访问队列的两边的时间复杂度为O(1)。访问中间的元素会被慢时间复杂度为O(n)。想要快速随机访问,用列表替代。

示例:

>>> 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 "<pyshell#6>", line 1, in -toplevel-    d.pop()IndexError: pop from an empty deque>>> d.extendleft('abc')              # extendleft() reverses the input order>>> ddeque(['c', 'b', 'a'])

双向队列食谱

本节展示了通过队列实现的各种处理方法
绑定队列的长度提供像在Unix tail过滤的相似功能

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

处理一个序列–最近被追回的在右面然后弹出到左边

def moving_average(iterable, n=3):    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) 

rotate()方法提供一种实现队列分片和删除的方式。例如,一个简单的del d[n]实例依赖于rotate()定位要被弹出的元素

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