标签: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
标签:for begin fast strong dex cti slow 队列 pre
原文地址:http://www.cnblogs.com/cathyj/p/7116185.html