亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python Queue:理解 FIFO 与 LIFO 及实战示例

Python Queue:理解 FIFO 与 LIFO 及实战示例

什么是 Python 队列?

队列是线性存储项的数据结构。项在尾部添加,从头部移除,遵循 先进先出(FIFO)原则。队列暴露两个逻辑端点:front 和 rear——在 rear 入队,从 front 出队。

本教程你将学到:

队列模块如何工作

行为类似现实排队:排在最前的人最先被服务。在队列数据结构中,最先入队的元素最先出队。

Python Queue:理解 FIFO 与 LIFO 及实战示例

rear 是插入新项的位置(如值 7)。front 是项离开队列的位置;移除第一项得到值 1。

因队列是线性的,无法直接移除中间任意元素;必须先出队所有前面的元素。

Python Queue:理解 FIFO 与 LIFO 及实战示例

Python 队列类型

Python queue 模块提供两个主要队列类:

开始使用:导入模块

Python 自带 queue 模块;无需外部安装。

import queue

实例化 FIFO 队列:

q1 = queue.Queue()

实例化 LIFO 队列:

q1 = queue.LifoQueue()

关键方法

Queue 和 LifoQueue 暴露相同的核心 API:

FIFO 队列示例

入队单个项

import queue
q1 = queue.Queue()
q1.put(10)  # 添加 10 到队列

带尺寸限制入队多项

q1 = queue.Queue(maxsize=5)  # 最多 5 项
for i in range(1, 6):
    q1.put(i)
print(q1.full())  # → True

输出:

True

出队项

item = q1.get()
print('Dequeued item:', item)

输出:

Dequeued item: 10

LIFO 队列示例

入队单个项

q1 = queue.LifoQueue()
q1.put(10)

出队项

item = q1.get()
print('Dequeued from LIFO:', item)

输出:

Dequeued from LIFO: 10

批量操作

FIFO – 入队 20 个数字

q1 = queue.Queue()
for i in range(20):
    q1.put(i)

FIFO – 全部出队

while not q1.empty():
    print('Value:', q1.get())

输出:

Value: 0
Value: 1
...
Value: 19

LIFO – 入队 20 个数字

q1 = queue.LifoQueue()
for i in range(20):
    q1.put(i)

LIFO – 全部出队

while not q1.empty():
    print('Value:', q1.get())

输出:

Value: 19
Value: 18
...
Value: 0

队列排序(冒泡排序)

q1 = queue.Queue()
for item in [11, 5, 4, 21, 3, 10]:
    q1.put(item)

n = q1.qsize()
for i in range(n):
    x = q1.get()
    for j in range(n-1):
        y = q1.get()
        if x > y:
            q1.put(y)
        else:
            q1.put(x)
        x = y
    q1.put(x)

while not q1.empty():
    print(q1.queue[0], end=' ')
    q1.get()

输出:

3 4 5 10 11 21

用递归反转队列

def reverse_queue(src, dest):
    item = src.get()
    if not src.empty():
        reverse_queue(src, dest)
    dest.put(item)
    return dest

q1 = queue.Queue()
for item in [11, 5, 4, 21, 3, 10]:
    q1.put(item)

q2 = queue.Queue()
reverse_queue(q1, q2)
while not q2.empty():
    print(q2.queue[0], end=' ')
    q2.get()

输出:

10 3 21 4 5 11

快速总结

Python

  1. FIFO与LIFO:核心差异、优缺点及实际应用场景
  2. 精通Python运算符:全面指南
  3. Python 列表操作:创建、访问、修改与进阶技巧
  4. 精通 Python 元组:创建、访问与进阶操作
  5. 精通 Python 字典:创建、操作与进阶技巧
  6. Python strip() 方法完全指南:去除首尾空白与自定义字符实战
  7. Python len() 函数实战指南:测量字符串、列表、元组、字典等对象长度
  8. 精通 Python yield:生成器 vs return 实战指南
  9. Python collections.Counter:高效计数、更新与算术运算
  10. 精通 Python enumerate():为列表、元组、字符串、字典带索引循环
  11. Python time.sleep():为代码添加延迟的完整指南
  12. Python list.index() 详解:查找元素位置的实用指南与示例