Python | 排队取奶茶

  • 队列的基本概念(队头、队尾)和特点(先入先出)

在 Python 语言中,标准库中的queue模块提供了多种队列的实现,比如普通队列和优先级队列,因此你可以使用queue.Queue类来创建队列,不过我们依旧可以使用列表来模拟队列的实现。

  • 获取队列的长度,即队列中元素的数量,通常使用列表的len()函数来获取
  • 判断队列是否为空,可以通过if not queue来判定
  • 入队操作,将新的元素添加到队列的尾部,使用列表的append()函数来实现
  • 出队操作,获取并移除队列的头部元素,可以通过pop(0)函数传递索引来实现。
  • 访问队列的头部元素,但不会将其移除,使用索引访问第一个元素queue[0]
python 复制代码
#导入queue模块
import queue

#创建一个对列
q = queue.Queue()

#通过put实现入队操作
q.put(1)
q.put(2)
q.put(3)

# 通过get()实现出队操作
item = q.get() #出队并返回队列中的元素
print(item)  #输出1

也可以用列表模拟队列(上道题用列表实现了栈):

python 复制代码
ueue = []

#入队操作
queue.append("Tom")
queue.append("Jerry")
queue.append("Mike")

#出队操作
remove_person = queue.pop(0)  #弹出并返回队列中的第一个元素

#判断队列是否为空:
if not queueL
    print("队列为空")
else:
    print(f"队头元素:{queue[0]}")

由此可见,在列表中,如果直接pop(),那么将会弹出列表的最末尾一个值;而如果pop(0),那么将会弹出列表中的第一个元素

按照列表模拟队列的写法如下:

python 复制代码
n = int(input())
persons = input().split()
m = int(input())

for _ in range(m):
    ope = input().split()
    opt = int(ope[0])
    if opt == 1:
        if persons:
            move_person = persons.pop(0)
    if opt == 2:
        persons.append(ope[1])
if persons:
    print(persons.pop(0))
else:
    print("There are no more people in the queue.")

按照queue模块的写法如下:

相关推荐
兆子龙1 小时前
ahooks useRequest 深度解析:一个 Hook 搞定所有请求
java·javascript
兆子龙1 小时前
React Suspense 从入门到实战:让异步加载更优雅
java·javascript
用户8356290780511 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon2 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly2 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程2 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
咕白m6253 小时前
Java 实现 Excel 转 HTML:完整示例
java
RealPluto4 小时前
Spring AOP 失效排查
java·spring
码路飞4 小时前
热榜全是 OpenClaw,但我用 50 行 Python 就造了个桌面 AI Agent 🤖
java·javascript