62

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?
4

4 に答える 4

68

len(queue)この場合、結果は 3 になります。

具体的には、関数はメソッド [参照リンク]len(object)を呼び出します。この場合のオブジェクトは で、メソッドを実装しています ( で確認できます)。object.__len__deque__len__dir(deque)


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

はい、空の場合は 0 になりますdeque

于 2012-09-22T23:24:48.113 に答える
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()))

添付のスクリーンショットで結果を確認してください

ここに画像の説明を入力

お役に立てれば...

于 2019-02-22T12:37:31.963 に答える