Python 資料結構之隊列的實現,python隊列

來源:互聯網
上載者:User

Python 資料結構之隊列的實現,python隊列

Python 隊列

Queue 隊列是一種先進先出(FIFO)的資料類型, 新的元素通過 入隊 的方式添加進 Queue 的末尾, 出隊 就是從 Queue 的頭部刪除元素.

用列表來做 Queue:

queue = []         # 初始化一個列表資料類型對象, 作為一個隊列def enQ():       # 定義一個入棧方法  queue.append(raw_input('Enter New String: ').strip())     # 提示輸入一個入隊的 String 對象, 調用 Str.strip() 保證輸入的 String 值不包含多餘的空格def deQ():        # 定義一個出隊方法  if len(queue) == 0:    print "Cannot pop from an empty queue!"  else:    print 'Remove [', `queue.pop(0)`, ']'    # 使用反單引號(` `)來代替 repr(), 把 String 的值用引號擴起來, 而不僅顯示 String 的值    # queue.pop(0) 總是將在隊列中最前面的元素彈出def viewQ():      # 定義一個顯示隊列中的內容的方法    print queueCMDs = {'u':enQ, 'o':deQ, 'v':viewQ}# 定義一個 Dict 類型對象, 將字元對應表到相應的 function .可以通過輸入字元來執行相應的操作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()        # Str.strip() 去除 String 對象前後的多餘空格        # Str.lower() 將多有輸入轉化為小寫, 便於後期的統一判斷        # 輸入 ^D(EOF, 產生一個 EOFError 異常)        # 輸入 ^C(中斷退出, 產生一個 keyboardInterrupt 異常)      except (EOFError, KeyboardInterrupt, IndexError):        choice = 'q'      print '\nYou picked: [%s]' % choice      if choice not in 'uovq':        print 'Invalid option, try again'      else:        break    if choice == 'q':      break    CMDs[choice]()    # 擷取 Dict 中字元對應的 functionName, 實現函數調用if __name__ == '__main__':  showmenu()

隊列和堆棧的實現方式很相似, 區別在於隊列總是先彈出第一個元素而堆棧總是先彈出最後一個元素.

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.