Python Deque
python deque
双端队列(deque)具有从任一端添加和删除元素的功能。deque模块是集合库的一部分。它具有添加和删除可以直接用参数调用的元素的方法。在下面的程序中,我们导入集合模块并声明一个双端队列。不需要任何类,我们直接使用内置的实现这些方法。
import collections # create a deque doubleended = collections.deque(["mon","tue","wed"]) print (doubleended) # append to the right print("adding to the right: ") doubleended.append("thu") print (doubleended) # append to the left print("adding to the left: ") doubleended.appendleft("sun") print (doubleended) # remove from the right print("removing from the right: ") doubleended.pop() print (doubleended) # remove from the left print("removing from the left: ") doubleended.popleft() print (doubleended) # reverse the dequeue print("reversing the deque: ") doubleended.reverse() print (doubleended)
当上面的代码被执行时,它会产生以下结果:
deque(['mon', 'tue', 'wed']) adding to the right: deque(['mon', 'tue', 'wed', 'thu']) adding to the left: deque(['sun', 'mon', 'tue', 'wed', 'thu']) removing from the right: deque(['sun', 'mon', 'tue', 'wed']) removing from the left: deque(['mon', 'tue', 'wed']) reversing the deque: deque(['wed', 'tue', 'mon'])