Python3 deque双向队列创建与使用方法详解
本文详细介绍Python3中deque双向队列的创建及常用操作方法,包括append、appendleft、clear、copy、count、extend、extendleft、index、insert、pop、popleft、remove、reverse和rotate等函数的具体用法与示例,帮助开发者高效掌握队列处理技巧。
Python3 deque双向队列概述
本文通过具体实例,详细解析Python3中deque双向队列的创建流程及其核心使用方法,旨在为读者提供实用的参考代码与操作指南。
deque基本创建与元素添加
在Python中,双向队列(deque)是collections模块提供的一种高效数据结构,支持从两端快速添加或删除元素。
import collections
d = collections.deque()
向队列右侧添加元素使用append方法。
import collections
d = collections.deque()
d.append(1)
d.append(2)
print(d)
执行上述操作后,控制台输出结果为:deque([1, 2])。
向队列左侧添加元素使用appendleft方法。
import collections
d = collections.deque()
d.append(1)
d.appendleft(2)
print(d)
执行上述操作后,控制台输出结果为:deque([2, 1])。
队列清空与拷贝操作
清空队列中的所有元素使用clear方法。
import collections
d = collections.deque()
d.append(1)
d.clear()
print(d)
执行上述操作后,控制台输出结果为:deque([])。
对队列进行浅拷贝使用copy方法。
import collections
d = collections.deque()
d.append(1)
new_d = d.copy()
print(new_d)
执行上述操作后,控制台输出结果为:deque([1])。
元素统计与队列扩展
统计指定元素在队列中出现的次数使用count方法。
import collections
d = collections.deque()
d.append(1)
d.append(1)
print(d.count(1))
执行上述操作后,控制台输出结果为:2。
从队列右侧扩展列表元素使用extend方法。
import collections
d = collections.deque()
d.append(1)
d.extend([3,4,5])
print(d)
执行上述操作后,控制台输出结果为:deque([1, 3, 4, 5])。
从队列左侧扩展列表元素使用extendleft方法。
import collections
d = collections.deque()
d.append(1)
d.extendleft([3,4,5])
print(d)
执行上述操作后,控制台输出结果为:deque([5, 4, 3, 1])。
元素查找与插入
查找指定元素的索引位置使用index方法。
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
print(d)
print(d.index('e'))
print(d.index('c',0,3)) #指定查找区间
执行上述操作后,控制台首先输出完整队列:deque(['a', 'b', 'c', 'd', 'e']),随后输出元素'e'的索引4,以及元素'c'在指定区间[0, 3)内的索引2。
在指定位置插入元素使用insert方法。
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
d.insert(2,'z')
print(d)
执行上述操作后,控制台输出结果为:deque(['a', 'b', 'z', 'c', 'd', 'e'])。
元素弹出与删除
获取并删除队列最右侧的元素使用pop方法。
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
x = d.pop()
print(x,d)
执行上述操作后,控制台输出结果为:e deque(['a', 'b', 'c', 'd'])。
获取并删除队列最左侧的元素使用popleft方法。
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
x = d.popleft()
print(x,d)
执行上述操作后,控制台输出结果为:a deque(['b', 'c', 'd', 'e'])。
删除队列中第一个匹配指定值的元素使用remove方法。
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
d.remove('c')
print(d)
执行上述操作后,控制台输出结果为:deque(['a', 'b', 'd', 'e'])。
队列反转与旋转
将队列中的元素顺序反转使用reverse方法。
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
d.reverse()
print(d)
执行上述操作后,控制台输出结果为:deque(['e', 'd', 'c', 'b', 'a'])。
将队列右侧的元素移动到左侧使用rotate方法。
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
d.rotate(2) #指定次数,默认1次
print(d)
执行上述操作后,控制台输出结果为:deque(['d', 'e', 'a', 'b', 'c'])。
相关资源与总结
如需进一步了解Python相关知识,建议查阅本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》。
希望本文所述内容能对您的Python程序设计工作有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









