【问题标题】:How to check deque length in Python如何在 Python 中检查双端队列长度
【发布时间】:2012-09-14 22:27:41
【问题描述】:

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

我没有看到他们在 Python 中提供 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)吗?这通常是 Python 处理元素计数的方式。
  • print(len(my_queue.queue)) 为我工作。
  • 我在编辑一个有这么多赞成票的问题时犹豫不决,但我认为在问题标题和正文中使用“队列”以外的词是有道理的,因为许多谷歌搜索有关 python @987654327 @ 将在这里结束,而接受的答案根本不适用于 Queue。 (是的,我知道 deque 也是一种队列 - 在这种情况下,这只是一个不幸的词......)
  • 计算queue.Queue(或multiprocessing.Queue)对象的长度,参考Get length of Queue in Python's multiprocessing library - Stack Overflow

标签: python python-3.x python-2.7 data-structures


【解决方案1】:

len(queue) 应该会给你结果,在这种情况下是 3。

具体来说,len(object) 函数将调用 object.__len__ 方法 [reference link]。而本例中的对象是deque,实现了__len__方法(可以通过dir(deque)看到)。


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

是的,对于空的deque,它将为 0。

【讨论】:

  • AttributeError: Queue instance has no attribute 'len' 我用 qsize() 代替 docs.python.org/2.7/library/queue.html
  • @memo:阅读问题正文。 collections.dequequeue.Queue 不同。后者预计将用于多线程情况,其中大小可能在另一个线程中更改。
  • 这个答案是错误的。根本没有这样的属性。
  • @SmallChess 你确定吗? collections.deque 确实存在,这就是问题所在。根据文档:docs.python.org/3/library/collections.html#deque-objects 在本节末尾... “除上述之外,双端队列还支持迭代、酸洗、len(d)、...” i>(强调我的)。
  • @SmallChess,确保它是 queue= deque([]) 而不是 queue= deque()
【解决方案2】:

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

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

上面的sn-p适用于Queue()类的python。感谢@rayryeng 的更新。

对于deque from collections,我们可以使用len(),如here K Z 所述。

【讨论】:

  • 请注意,这是针对Queue 类的,它与来自collections.deque 的类不同,这是OP 实际要求的。
  • @rayryeng 但它让像我这样的谷歌用户得到了他们确实期望的答案!不知道为什么queue.Queue 类没有固定长度……
【解决方案3】:

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

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()))

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

希望这会有所帮助...

【讨论】:

    【解决方案4】:

    使用queue.rear+1获取队列长度

    【讨论】:

    • 不,不会的。在 Python 语言中看到的任何队列中都没有 rear 属性,至少在核心堆栈中没有。
    猜你喜欢
    • 2014-11-25
    • 2020-09-24
    • 2020-06-14
    • 2017-05-06
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2023-04-02
    相关资源
    最近更新 更多