Python-design-patterns-queues

提供:Dev Guides
移動先:案内検索

Pythonデザインパターン-キュー

キューはオブジェクトのコレクションであり、FIFO(ファーストインファーストアウト)およびLIFO(ラストインファーストアウト)の手順に従って単純なデータ構造を定義します。 挿入および削除操作は、 enqueue および dequeue 操作と呼ばれます。

キューは、含まれるオブジェクトへのランダムアクセスを許可しません。

FIFO手順の実装方法

次のプログラムは、FIFOの実装に役立ちます-

import Queue

q = Queue.Queue()

#put items at the end of the queue
for x in range(4):
   q.put("item-" + str(x))

#remove items from the head of the queue
while not q.empty():
   print q.get()

出力

上記のプログラムは、次の出力を生成します-

Fifo

LIFO手順の実装方法は?

次のプログラムは、LIFO手順の実装に役立ちます-

import Queue

q = Queue.LifoQueue()

#add items at the head of the queue
for x in range(4):
   q.put("item-" + str(x))

#remove items from the head of the queue
while not q.empty():
   print q.get()

出力

上記のプログラムは、次の出力を生成します-

Lifo

優先度キューとは何ですか?

優先度キューは、指定されたデータ構造内の最小または最大のキーを持つレコードへの迅速なアクセスを提供するために、順序付けられたキーを持つレコードのセットを管理するコンテナデータ構造です。

優先度キューを実装する方法は?

優先度キューの実装は次のとおりです-

import Queue

class Task(object):
   def __init__(self, priority, name):
      self.priority = priority
      self.name = name

   def __cmp__(self, other):
      return cmp(self.priority, other.priority)

q = Queue.PriorityQueue()

q.put( Task(100, 'a not agent task') )
q.put( Task(5, 'a highly agent task') )
q.put( Task(10, 'an important task') )

while not q.empty():
   cur_task = q.get()
    print 'process task:', cur_task.name

出力

上記のプログラムは、次の出力を生成します-

優先度キュー