栈
可以直接使用python 中的列表
入栈使用 append
出栈使用 pop
# 栈
stack = [3,4,5,6,7]
stack.append(8)
# stack
[3,4,5,6,7,8]
stack.pop() # 8
stack
# [3,4,5,6,7]
队列
Python的Queue模块提供一种适用于多线程编程的先进先出(FIFO)容器
使用: put() 将元素添加到序列尾端,get()从队列中取出数据并返回该数据内容。
from queue import Queue
#from queue import Queue #put #get
q = Queue()
for i in range(3):
q.put(i)
while not q.empty():
print(q.get())
#
0
1
2
双端队列 collections.deque
官方文档
https://docs.python.org/3.6/library/collections.html#collections.deque
deque 是一个双端队列, 如果要经常从两端append 的数据, 选择这个数据结构就比较好了, 如果要实现随机访问,不建议用这个,请用列表.
deque 优势就是可以从两边append ,appendleft 数据. 这一点list 是没有的.
append(‘a’)右边入队列,appendleft(‘a’)左边。
pop()右边删除,popleft()左边删除。
count(x) 计算队列中等于x 的个数
rotate() 所有元素向右移动一格,为负数则向左移动
append(x)
Add x to the right side of the deque.
appendleft(x)
Add x to the left side of the deque.
insert(i, x)
Insert x into the deque at position i.
pop()
Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError.
popleft()
Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.
reverse()
Reverse the elements of the deque in-place and then return None.
rotate(n=1)
Rotate the deque n steps to the right. If n is negative, rotate to the left.
count(x)
Count the number of deque elements equal to x.
from collections import deque
# from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.appendleft('a')
queue.append('b')
print(queue)
#deque(['a', 'Eric', 'John', 'Michael', 'b'])
queue.popleft() # The first to arrive now leaves
queue.pop()
print(queue)
#deque(['Eric', 'John', 'Michael'])
本文介绍了如何在Python中使用列表实现栈,以及Queue模块的先进先出队列操作。特别关注了collections.deque的双端队列特性,包括append、appendleft、pop和popleft等方法。通过实例演示了这些数据结构在实际编程中的应用场景。
3465

被折叠的 条评论
为什么被折叠?



