首页 > 代码库 > Python基础学习(五)
Python基础学习(五)
使用Lists用作为堆栈or队列
#Using Lists as Stacks
"""The list methods make it very easy to use a list as a stack, where the last element added is the first
element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append().
To retrieve an item from the top of the stack, use pop() without an explicit index."""
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print(stack)
stack.pop()
print(stack)
stack.pop()
stack.pop()
print(stack)
#Using Lists as Queues
"""It is also possible to use a list as a queue, where the first element added is the first element retrieved
(“first-in, first-out”); however, lists are not efficient for this purpose.
While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow
(because all of the other elements have to be shifted by one)."""
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")
queue.append("Graham")
queue.popleft()
queue.popleft()
print(queue)
当做队列使用时,需要引入collections.deque
运行结果:
D:\Python3.6.1\python.exe F:/python_workspace/tutorial/Lists2.py
[3, 4, 5, 6, 7]
[3, 4, 5, 6]
[3, 4]
deque([‘Michael‘, ‘Terry‘, ‘Graham‘])
Process finished with exit code 0
Python基础学习(五)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。