在 Python 中获取队列的第一个元素
在 Python 中使用 get()
方法获取队列的第一个元素。 get()
方法从队列中移除并返回一个项目。 如果我们不想删除该元素,请使用队列上的 queue 属性并访问索引 0 处的元素。
import queue
q = queue.Queue()
for item in range(15):
q.put(item)
print(q.queue[0]) # 👉️ 0 在不删除它的情况下获得第一个
# 👇️ 从队列中移除并返回一个项目
print(q.get()) # 👉️ 0 (get first)
print(q.get()) # 👉️ 1 (get second)
print(q.get()) # 👉️ 2 (get third)
如果我们使用集合模块中的 deque
对象,请向下滚动到下一个代码片段。
queue
属性使我们能够访问deque
对象,并且deque
对象支持popleft()
操作和索引。
如果我们不想删除队列的特定元素而只想访问它,请使用 q.queue[0]
。
queue.get()
方法从队列中移除并返回一个项目。
如果使用 collections.deque
类,则可以通过访问索引 0 处的 deque 对象来访问队列中的第一个元素。
from collections import deque
deq = deque(['a', 'b', 'c'])
print(deq[0]) # 👉️ get first
print(deq[1]) # 👉️ get second
print(deq[2]) # 👉️ get third
first = deq.popleft()
print(first) # 👉️ 'a'
print(deq) # 👉️ deque(['b', 'c'])
Deque 对象支持索引,因此获取队列的第一个元素与获取列表的第一个元素相同。
双端队列对象也支持 popleft()
方法。
该方法从双端队列的左侧移除并返回一个元素。
如果双端队列中不存在任何元素,则该方法会引发 IndexError
。
如果我们需要从双端队列的右侧删除并返回一个元素,请使用 pop()
方法。
from collections import deque
deq = deque(['a', 'b', 'c'])
print(deq[0]) # 👉️ get first
first = deq.popleft()
print(first) # 👉️ 'a'
print(deq) # 👉️ deque(['b', 'c'])
last = deq.pop()
print(last) # 👉️ 'c'
print(deq) # 👉️ deque(['b'])
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。