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

Python Deque 模块使用详解

WBOY
Release: 2016-06-16 08:43:32
Original
1311 people have browsed it

创建Deque序列:

from collections import deque

d = deque()
Copy after login

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

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

输出结果:

  3
  '1'
  '3'
Copy after login

两端都使用pop:

  d = deque('12345')
  len(d)
  d.popleft()
  d.pop()
  d
Copy after login

输出结果:

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

我们还可以限制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)
Copy after login

添加list中各项到deque中:

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

输出结果:

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template