Python实现队列的方法

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Python 比较两个数组的元素的异同方法

通过set()获取两个数组的交/并/差集: print set(a).intersection(set(b)) # 交集 print set(a).union(set(b)) # 并...

Python3 适合初学者学习的银行账户登录系统实例

一、所用知识点: 1. for循环与if判断的结合 2. %s占位符的使用 3. 辅助标志的使用(标志位) 4. break的使用 二、代码示例: ''' 银行登录系统 ''' u...

python getopt 参数处理小示例

opts, args = getopt.getopt(sys.argv[1:], "t:s:h", ["walletype=", "servicename=",'help']) for...

python系统指定文件的查找只输出目录下所有文件及文件夹

python系统指定文件的查找只输出目录下所有文件及文件夹

修改python运行路径 import os os.chdir('C:/Users/86177/Desktop') os.chdir(r'C:\Users\86177\Desktop...

在Pytorch中计算卷积方法的区别详解(conv2d的区别)

在二维矩阵间的运算: class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=...