How Does Deque Work in Python

左心房为你撑大大i 提交于 2020-01-22 16:00:35

问题


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 Example - Understood

stack = ["a", "b", "c"]

# push operation
stack.append("e")
print(stack)

# pop operation
stack.pop()
print(stack)

As expected when pushing and popping, the "e" goes Last In, First Out (LIFO). My question is with the example below.

Queue Example - Not Understanding

from collections import deque

dq = deque(['a','b','c'])
print(dq)

# push
dq.append('e')
print(dq)

# pop
dq.pop()
print(dq)

When pushing and popping, the "e" goes Last In, First Out (LIFO). Shouldn't it be First In, First Out (FIFO)?


回答1:


A deque is a generalization of stack and a queue (It is short for "double-ended queue").

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.



来源:https://stackoverflow.com/questions/38679914/how-does-deque-work-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!