本文实例讲述了python实现队列的方法。分享给大家供大家参考。具体实现方法如下:
#!/usr/bin/env python
queue = []
def enq():
queue.append(raw_input(‘enter new string: ‘).strip())
#调用list的列表的pop()函数.pop(0)为列表的第一个元素
def deq():
if len(queue) == 0:
print ‘cannot pop from an empty queue!’
else:
print ‘removed [‘, queue.pop(0) ,’]’
def viewq():
print queue
cmds = {‘e’: enq, ‘d’: deq, ‘v’: viewq}
def showmenu():
pr = “””
(e)nqueue
(d)equeue
(v)iew
(q)uit
enter choice: “””
while true:
while true:
try:
choice = raw_input(pr).strip()[0].lower()
except (eoferror, keyboardinterrupt, indexerror):
choice = ‘q’
print ‘\nyou picked: [%s]’ % choice
if choice not in ‘devq’:
print ‘invalid option, try again’
else:
break
if choice == ‘q’:
break
cmds[choice]()
if __name__ == ‘__main__’:
showmenu()
希望本文所述对大家的python程序设计有所帮助。