Python标准库collections.deque自用整理

Python 3.7.7 文档
collections - Container datatypes
deque读作“deck”(“double-ended queue”)

  • Returns a newdequeobject initialized left-to-right (using append()) withdata from iterable. If iterarble is not specified, the newdeque is empty.
  • 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.
Method 作用
maxlen deque的最大长度,maxlen值为None则没有大小限制
append(x) 在deque右端加入元素x
appendleft(x) 在deque左端加入元素x
clear() 清空队列,deque长度变为0
copy() Create a shallow copy of the deque
count(x) 计算deque中等于x的元素的数量
extend(iterable) 在右端逐个添加iterable参数中的元素
extendleft(iterable) 在左端逐个添加iterable参数中的元素 ;添加部分的显示顺序和extend中相反
index(x[, start[, stop]]) 与list的index方法相似 or 返回ValueError
insert(i, x) 与list的insert方法相似 or 插入元素使得长度超过maxlen时, 返回IndexError
pop() 删除并返回最右端元素 or 无元素时,返回IndexError
popleft() 删除并返回最左端元素 or 无元素时,返回IndexError
remove(x) 删除第一个出现的x值,没有的话返回ValueError
reverse() Reverse the elements of the deque in-place and then return None
rotate(n=1) n值为正,向右转动;n值为负,向左转动;rotate(n=-1)等价于d.appendleft(d.pop()), rotate(n=-1)等价于d.append(d.popleft())
  • Deques support iteration, pickling, len(d), reversed(d), copy.copy(d), copy.deepcopy(d), membership testing with the in 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.
>>> from collections import deque
# 创建 deque
>>> d = deque()
>>> d
deque([])
>>> d = deque(maxlen=None)
>>> d
deque([])
>>> d = deque(maxlen = 5)
>>> d = deque('python', maxlen = 5)
>>> d
deque(['y', 't', 'h', 'o', 'n'], maxlen=5)
>>> d = deque((2,5))
>>> d
deque([2, 5])
>>> d = deque((2,))
>>> d
deque([2])
# 其它
>>> d = deque('python')
>>> for elem in d:
    print(elem.upper())
    
P
Y
T
H
O
N
>>> d.pop()
'n'
>>> d.popleft()
'p'
>>> d[0]   # 支持indexed access
'y'
>>> d[-1]
'o'
>>> list(reversed(d))  # 支持reversed(d),支持list()
['o', 'h', 't', 'y']
>>> d
deque(['y', 't', 'h', 'o'])  # d没有发生变化
>>> 'h' in d  #至此用in operator来检测membership
True
>>> d.rotate(-1)
>>> d
deque(['t', 'h', 'o', 'y'])
>>> deque(reversed(d))
deque(['y', 'o', 'h', 't'])
>>> d.clear()
>>> d.pop()
Traceback (most recent call last):
  File "<pyshell#55>", line 1, in <module>
    d.pop()
IndexError: pop from an empty deque
>>> d.extend('abc')
>>> d
deque(['a', 'b', 'c'])
>>> d.extendleft('abc')
>>> d
deque(['c', 'b', 'a', 'a', 'b', 'c'])
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容