How Does Deque Work in Python(双端队列在 Python 中是如何工作的)
问题描述
在尝试在 Python 中重新创建队列和堆栈时,我无法理解以下代码片段中双端队列的工作原理.
I am having trouble understanding how the deque works in the snippet of code below, while trying to recreate a queue and a stack in Python.
堆栈示例 - 了解
stack = ["a", "b", "c"]
# push operation
stack.append("e")
print(stack)
# pop operation
stack.pop()
print(stack)
正如预期的那样,在推入和弹出时,e"是后进先出 (LIFO).我的问题是下面的例子.
As expected when pushing and popping, the "e" goes Last In, First Out (LIFO). My question is with the example below.
队列示例 - 不理解
from collections import deque
dq = deque(['a','b','c'])
print(dq)
# push
dq.append('e')
print(dq)
# pop
dq.pop()
print(dq)
当推动和弹出时,e"进入后进先出 (LIFO).不应该是先进先出(FIFO)吗?
When pushing and popping, the "e" goes Last In, First Out (LIFO). Shouldn't it be First In, First Out (FIFO)?
推荐答案
双端队列是栈和队列的概括(双端队列"的简称).
因此,pop() 操作仍然使它像一个堆栈一样,就像它作为一个列表一样.要使其像队列一样,请使用 popleft() 命令.Deques 被用来支持这两种行为,这样 pop() 函数在数据结构中是一致的.为了使双端队列像队列一样工作,您必须使用与队列对应的函数.因此,在第二个示例中将 pop() 替换为 popleft(),您应该会看到预期的 FIFO 行为.
Thus, the pop() operation still causes it to act like a stack, just as it would have as a list. To make it act like a queue, use the popleft() command. Deques are made to support both behaviors, and this way the pop() function is consistent across data structures. In order to make the deque act like a queue, you must use the functions that correspond to queues. So, replace pop() with popleft() in your second example, and you should see the FIFO behavior that you expect.
双端队列还支持最大长度,这意味着当您向双端队列添加大于最大长度的对象时,它将从另一端丢弃"一些对象以保持其最大大小.
Deques also support a max length, which means when you add objects to the deque greater than the maxlength, it will "drop" a number of objects off the opposite end to maintain its max size.
这篇关于双端队列在 Python 中是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:双端队列在 Python 中是如何工作的
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01