当前位置:首页>python>Python队列

Python队列

  • 2026-08-24 19:13:44
Python队列

什么是队列?

想象你在食堂排队打饭:

  • 先来的同学排在前面(入队)
  • 厨师从队伍最前面开始打饭(出队)
  • 这就是“先进先出”(FIFO)原则

Python中的队列实现方式

1. 使用列表(简单但效率低)

# 创建队列queue = []# 入队(添加元素到末尾)queue.append('小明')queue.append('小红')queue.append('小刚')print(f"排队情况:{queue}")  # ['小明', '小红', '小刚']# 出队(从前面移除元素)first_person = queue.pop(0)print(f"{first_person} 打完饭了")  # 小明打完饭了print(f"剩余队伍:{queue}")  # ['小红', '小刚']

问题:pop(0)效率低,因为要移动所有元素

2. 使用 collections.deque(推荐!)

from collections import deque# 创建高效队列queue = deque()# 入队queue.append('小明')  # 从右边添加queue.append('小红')queue.append('小刚')print(f"排队情况:{queue}")  # deque(['小明', '小红', '小刚'])# 出队first_person = queue.popleft()  # 从左边移除print(f"{first_person} 打完饭了")  # 小明打完饭了print(f"剩余队伍:{queue}")  # deque(['小红', '小刚'])# 查看队首(但不移除)next_person = queue[0]print(f"下一个是:{next_person}")  # 小红# 查看队列长度print(f"还有 {len(queue)} 人等待")  # 还有 2 人等待

3. 使用 queue.Queue(线程安全)

from queue import Queue# 创建队列q = Queue(maxsize=3)  # 设置最大容量# 入队q.put('任务1')q.put('任务2')q.put('任务3')# 队列已满print(f"队列是否满?{q.full()}")  # True# 出队task = q.get()print(f"处理任务:{task}")  # 处理任务:任务1# 队列是否为空print(f"队列是否空?{q.empty()}")  # False# 队列当前大小print(f"队列中有 {q.qsize()} 个任务")

实际应用场景

场景1:打印机任务队列

from collections import dequeclass Printer:    def __init__(self):        self.print_queue = deque()    def add_print_job(self, document):        self.print_queue.append(document)        print(f"📄 添加打印任务:{document}")    def print_next(self):        if self.print_queue:            document = self.print_queue.popleft()            print(f"🖨️  正在打印:{document}")        else:            print("✅ 没有待打印的任务")# 使用打印机printer = Printer()printer.add_print_job("报告.pdf")printer.add_print_job("简历.docx")printer.add_print_job("照片.jpg")printer.print_next()  # 打印:报告.pdfprinter.print_next()  # 打印:简历.docx

场景2:客服系统(先来先服务)

class CustomerService:    def __init__(self):        self.waiting_queue = deque()    def customer_arrives(self, name):        self.waiting_queue.append(name)        position = len(self.waiting_queue)        print(f"👤 {name} 进入排队,您前面有 {position-1} 人")    def serve_customer(self):        if self.waiting_queue:            customer = self.waiting_queue.popleft()            print(f"✅ 正在为 {customer} 服务")            print(f"📢 提醒:下一位是 {self.waiting_queue[0] if self.waiting_queue else'无'}")        else:            print("💤 暂无客户等待")# 客服系统工作流程cs = CustomerService()cs.customer_arrives("张三")cs.customer_arrives("李四")cs.customer_arrives("王五")cs.serve_customer()  # 服务张三cs.serve_customer()  # 服务李四

队列操作总结

操作
列表实现
deque实现
含义
入队
append(item)append(item)
添加元素到末尾
出队
pop(0)popleft()
移除并返回第一个元素
查看队首
list[0]deque[0]
查看但不移除第一个元素
判断空
len(list)==0len(deque)==0
检查队列是否为空

记忆技巧

  1. 队列就像排队
    先来先服务
  2. deque发音
    "deck",像一副牌,从一端抽牌
  3. 操作方向
  • append()
    从右边进入(排队)
  • popleft()
    从左边离开(服务)

小练习

# 尝试实现一个面包店队列系统bakery_queue = deque()# 你的代码:# 1. 让3个顾客排队# 2. 服务1个顾客# 3. 再来1个顾客# 4. 查看下一个要服务的顾客# 参考答案:bakery_queue.append("顾客A")bakery_queue.append("顾客B")bakery_queue.append("顾客C")served = bakery_queue.popleft()print(f"已服务:{served}")bakery_queue.append("顾客D")next_customer = bakery_queue[0]print(f"下一个:{next_customer}")print(f"当前队列:{list(bakery_queue)}")

队列 = 排队 = 先进先出!选择deque来实现效率最高。

最新文章

随机文章