Python Deque 模块使用详解

yipeiwu_com6年前Python基础

创建Deque序列:

from collections import deque

d = deque()

Deque提供了类似list的操作方法:

  d = deque()
  d.append('1')
  d.append('2')
  d.append('3')
  len(d)
  d[0]
  d[-1]

输出结果:

  3
  '1'
  '3'

两端都使用pop:

  d = deque('12345')
  len(d)
  d.popleft()
  d.pop()
  d

输出结果:

  5
  '1'
  '5'
  deque(['2', '3', '4'])

我们还可以限制deque的长度:

    d = deque(maxlen=30)

当限制长度的deque增加超过限制数的项时, 另一边的项会自动删除:

  d = deque(maxlen=2)
  d.append(1)
  d.append(2)
  d
  d.append(3)
  d
  deque([1, 2], maxlen=2)
  deque([2, 3], maxlen=2)

添加list中各项到deque中:

  d = deque([1,2,3,4,5])
  d.extendleft([0])
  d.extend([6,7,8])
  d

输出结果:

  deque([0, 1, 2, 3, 4, 5, 6, 7, 8])

相关文章

在Django的通用视图中处理Context的方法

制作友好的模板Context 你也许已经注意到范例中的出版商列表模板在变量 object_list 里保存所有的书籍。这个方法工作的很好,只是对编写模板的人不太友好。 他们必须知道这里正...

pycharm 取消默认的右击运行unittest的方法

取消默认的右击运行unittest方法: File-> Settings -> Tools -> Python Integrated Tools -> Defau...

matplotlib作图添加表格实例代码

matplotlib作图添加表格实例代码

本文所示代码主要是通过Python+matplotlib实现作图,并且在图中添加表格的功能,具体如下。 代码 import matplotlib.pyplot as plt impo...

python 遍历列表提取下标和值的实例

如下所示: for index,value in enumerate(['apple', 'oppo', 'vivo']): print(index,value) 以上这篇py...

python mqtt 客户端的实现代码实例

这篇文章主要介绍了python mqtt 客户端代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 安装paho-mqtt...