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

How Does Deque Work in Python(双端队列在 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 中是如何工作的

基础教程推荐