如何在Python中检查deque的长度?
我没有看到他们提供deque.length...
http://docs.python.org/tutorial/datastructures.html
from collections import deque
queue = deque(["Eric", "John", "Michael"])
如何检查这个双端队列的长度?
我们可以像这样初始化吗?
queue = deque([]) #is this length 0 deque?
如何在Python中检查deque的长度?
我没有看到他们提供deque.length...
http://docs.python.org/tutorial/datastructures.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?
空的deque
会返回 0。
collections.deque
与queue.Queue
是不同的。后者预期在多线程情况下使用,其中大小可能会在另一个线程中更改。 - jfscollections.deque
绝对存在,这也是问题所问的。根据文档:https://docs.python.org/3/library/collections.html#deque-objects,在该部分的末尾...“除了上述内容,deque还支持迭代、pickling、**len(d)**…”(重点在于len(d))。 - rayryengQueue
类的说明,它与collections.deque
中的不同,而后者才是OP实际要求的。 - rayryengqueue.Queue
类没有常规长度... - gerrit是的,我们可以检查从collections创建的队列对象的长度。
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()))
请查看附加的屏幕截图以获取结果。
希望这可以帮到您…queue.rear+1
来获取队列的长度。rear
属性,至少不在核心堆栈中。 - rayryengcollections.deque
,而不是你在大学里的循环队列作业。 - nurettin
len(queue)
吗?通常这是Python处理元素计数的方式。 - mjgpy3print(len(my_queue.queue))
对我有用。 - rustyMagnetQueue
的谷歌搜索结果都会指向这里,而被接受的答案对于Queue
将不起作用。(是的,我知道deque
也是队列的一种类型——在这种情况下只是一个不幸的词...) - Colin T Bowersqueue.Queue
(或multiprocessing.Queue
)对象的长度,请参考 Get length of Queue in Python's multiprocessing library - Stack Overflow。 - user202729