Home  >  Article  >  Backend Development  >  Python Deque 模块使用详解

Python Deque 模块使用详解

WBOY
WBOYOriginal
2016-06-16 08:43:321268browse

创建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])

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn