如何在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?
len(queue)
应该会给你结果,在本例中为 3。具体来说,
len(object)
函数将调用
object.__len__
方法[参考链接]。而本例中的对象是
deque
,它实现了
__len__
方法(你可以通过
dir(deque)
看到它)。
queue= deque([]) #is this length 0 queue?
是的,空时将为 0
deque
。
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()))
检查所附屏幕截图中的结果
希望这有帮助...
“属性错误: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))