python中栈、队列

可以直接使用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'])
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值