Автор оригинала: Pankaj Kumar.
В этой статье мы рассмотрим модуль очереди Python, который является интерфейсом для структуры данных очереди.
Очередь Python
Очередь-это структура данных, в которой первый вставляемый элемент также является первым выскочившим элементом. Это похоже на реальную очередь, где первый в очереди также является первым, кто вышел.
В Python мы можем использовать модуль queue
для создания очереди объектов.
Это часть стандартной библиотеки Python, поэтому нет необходимости использовать pip
.
Импортируйте модуль с помощью:
import queue
Чтобы создать объект очереди, мы можем создать его экземпляр с помощью:
q = queue.Queue()
По умолчанию это значение равно 0, но если вы хотите явно упомянуть об этом, вы можете сделать это с помощью:
q = queue.Queue(max_capacity)
Методы Queue.get() и Queue.put()
Мы можем вставлять и извлекать значения в очередь с помощью методов queue.get()
и queue.put ()
.
Давайте создадим очередь и вставим числа от 1 до 5.
import queue # Instantiate the Queue object q = queue.Queue() # Insert elements 1 to 5 in the queue for i in range(1, 6): q.put(i) print('Now, q.qsize() =', q.qsize()) # Now, the queue looks like this: # (First) 1 <- 2 <- 3 <- 4 <- 5 for i in range(q.qsize()): print(q.get())
Выход
Now, q.qsize() = 5 1 2 3 4 5
Выход
Выход
Выход
import queue # Instantiate the Queue object q = queue.Queue() # Insert elements 1 to 5 in the queue for i in range(1, 6): q.put(i) print('Now, q.qsize() =', q.qsize()) # Empty queue q.empty() print('After emptying, size =', q.qsize()) for i in range(q.qsize()): print(q.get())
Выход
Now, q.qsize() = 5 After emptying, size = 0
Выход
Выход
Выход
class MyQueue(): # Using Python Lists as a Queue def __init__(self): self.queue = [] def enqueue(self, value): # Inserting to the end of the queue self.queue.append(value) def dequeue(self): # Remove the furthest element from the top, # since the Queue is a FIFO structure return self.queue.pop(0) my_q = MyQueue() my_q.enqueue(2) my_q.enqueue(5) my_q.enqueue(7) for i in my_q.queue: print(i) print('Popped,', my_q.dequeue()) for i in my_q.queue: print(i)
Выход
2 5 7 Popped, 2 5 7
Выход
Выход
Выход
Выход
Выход
import queue priority_q = queue.PriorityQueue() priority_q.put((1, 'Hello')) priority_q.put((3, 'AskPython')) priority_q.put((2, 'from')) for i in range(priority_q.qsize()): print(priority_q.get())
Выход
(1, 'Hello') (2, 'from') (3, 'AskPython')
Выход
Выход
Выход
>>> import heapq >>> q = [] >>> heapq.heappush(q, (1, 'hi')) >>> q [(1, 'hi')] >>> heapq.heappush(q, (3, 'AskPython')) >>> q [(1, 'hi'), (3, 'AskPython')] >>> heapq.heappush(q, (2, 'from')) >>> q [(1, 'hi'), (3, 'AskPython'), (2, 'from')] >>> heapq.heappop(q) (1, 'hi') >>> heapq.heappop(q) (2, 'from') >>> heapq.heappop(q) (3, 'AskPython') >>> heapq.heappop(q) Traceback (most recent call last): File "", line 1, in IndexError: index out of range
Выход
import heapq q = [] heapq.heappush(q, (2, 'from')) heapq.heappush(q, (1, 'Hello')) heapq.heappush(q, (3, 'AskPython')) while q: # Keep popping until the queue is empty item = heapq.heappop(q) print(item)
Выход
(1, 'Hello') (2, 'from') (3, 'AskPython')
Выход
Выход