双端队列在 Python 中是如何工作的

编程入门 行业动态 更新时间:2024-10-08 13:29:43
本文介绍了双端队列在 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 中是如何工作的

本文发布于:2023-11-30 06:47:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649068.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:队列   工作   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!