码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础学习(五)

时间:2017-07-04 14:45:33      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:for   begin   fast   strong   dex   cti   slow   队列   pre   

使用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基础学习(五)

标签:for   begin   fast   strong   dex   cti   slow   队列   pre   

原文地址:http://www.cnblogs.com/cathyj/p/7116185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!