如何在Python中检查双端队列长度

问题描述 投票:0回答:4

如何在Python中检查双端队列的长度?

我没有看到他们在 Python 中提供 deque.length...

http://docs.python.org/tutorial/datastructs.html

from collections import deque
queue = deque(["Eric", "John", "Michael"])

如何检查这个双端队列的长度?

我们可以像这样初始化吗?

queue = deque([]) #is this length 0 deque?
    
python python-3.x python-2.7 data-structures
4个回答
83
投票

len(queue)

 应该会给你结果,在本例中为 3。

具体来说,

len(object)

函数将调用
object.__len__
方法[
参考链接]。而本例中的对象是deque
,它实现了
__len__
方法(你可以通过
dir(deque)
看到它)。


queue= deque([]) #is this length 0 queue?

是的,空时将为 0

deque


64
投票
很简单,只需使用 .qsize() 示例:

a=Queue() a.put("abcdef") print a.qsize() #prints 1 which is the size of queue

上面的代码片段适用于Python的

Queue()

类。感谢 
@rayryeng 的更新。

对于

deque from collections

,我们可以使用 
len()
,如 
K Z here所述。


1
投票
是的,我们可以检查从集合创建的队列对象的长度。

from collections import deque class Queue(): def __init__(self,batchSize=32): #self.batchSie = batchSize self._queue = deque(maxlen=batchSize) def enqueue(self, items): ''' Appending the items to the queue''' self._queue.append(items) def dequeue(self): '''remoe the items from the top if the queue becomes full ''' return self._queue.popleft()

创建类的对象

q = Queue(batchSize=64) q.enqueue([1,2]) q.enqueue([2,3]) q.enqueue([1,4]) q.enqueue([1,22])

现在检索队列的长度

#check the len of queue print(len(q._queue)) #you can print the content of the queue print(q._queue) #Can check the content of the queue print(q.dequeue()) #Check the length of retrieved item print(len(q.dequeue()))

检查所附屏幕截图中的结果

希望这有帮助...


0
投票
如果您遇到错误所在的问题

“属性错误:collections.deque没有属性长度”

那么原因是你可能在Python中使用了JavaScript语法,即你试图调用

from collections import deque q = deque() q.append(2) q.length # This is wrong
获取双端队列长度的正确方法就是Pythonic 

len()

函数

from collections import deque q = deque() q.append(2) print(len(q))
    
© www.soinside.com 2019 - 2024. All rights reserved.