python栈、队列的使用
栈
#栈
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
#stack
[3, 4, 5, 6, 7]
stack.pop()
#7
stack
#[3, 4, 5, 6]
stack.pop()
#6
queue
Python的Queue模块提供一种适用于多线程编程的先进先出(FIFO)容器 使用:put(),将元素添加到序列尾端,get(),从队列尾部移除元素。
Queue.Queue(maxsize=0) FIFO, 如果maxsize小于1就表示队列长度无限
Queue.LifoQueue(maxsize=0) LIFO, 如果maxsize小于1就表示队列长度无限
Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空,返回True,反之False
Queue.full() 如果队列满了,返回True,反之False
Queue.get([block[, timeout]]) 读队列,timeout等待时间
Queue.put(item, [block[, timeout]]) 写队列,timeout等待时间
Queue.queue.clear() 清空队列
from queue import Queue
q = Queue()
for i in range(3):
q.put(i)
while not q.empty():
print(q.get())
#
0
1
2
LifoQueue
使用后进先出序
from queue import LifoQueue
q = LifoQueue()
for i in range(3):
q.put(i)
while not q.empty():
print(q.get())
#
2
1
0
PriorityQueue
依据队列中内容的排序顺序(sort order)来决定那个元素将被检索
from queue import PriorityQueue
class Job(object):
def __init__(self, priority, description):
self.priority = priority
self.description = description
print('New job:', description)
return
def __lt__(self, other):
#定义小于操作符(<)的行为
return self.priority < other.priority
q = PriorityQueue()
#q.put((数字,值)),特点:数字越小,优先级越高
q.put(Job(5, 'Mid-level job'))
q.put(Job(10, 'Low-level job'))
q.put(Job(1, 'Important job'))
while not q.empty():
next_job = q.get()
print('Processing job', next_job.description)
#
New job: Mid-level job
New job: Low-level job
New job: Important job
Processing job: Important job
Processing job: Mid-level job
Processing job: Low-level job
collections.deque模块
是python标准库collections中的一项,它提供了两端都可以操作的序列,这意味着,在序列的前后你都可以执行添加或删除操作。
append('a')右边入队列,appendleft('a')左边。
pop()右边删除,popleft()左边删除。
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'])