print("append from left") dq.appendleft(1) print(dq)
print("append from right") dq.append("foo") print(dq)
deque([1, '2', 'foo'])
pop from left
deque(['2', 'foo'])
pop from right
deque(['2'])
append from left
deque([1, '2'])
append from right
deque([1, '2', 'foo'])
我们可以通过设置队列的最大长度,从而自动地从队首弹出和队尾退出。
1 2 3 4 5 6 7 8 9 10 11 12 13
dq2=deque(maxlen=8)
for i in range(8): dq2.append(i)
print(dq2)
print("Be about to append 8 at right most!\n") print("After reach max length of the deque, \ the left most element will be poped out automatically!\n") dq2.append(8) print(dq2)
deque([0, 1, 2, 3, 4, 5, 6, 7], maxlen=8)
Be about to append 8 at right most!
After reach max length of the deque, the left most element will be poped out automatically!
deque([1, 2, 3, 4, 5, 6, 7, 8], maxlen=8)
[('__class__', <class '__main__.TestClass'>), ('__delattr__', <method-wrapper '__delattr__' of TestClass object at 0x112940978>), ('__dict__', {'a': 1, 'b': 2}), ('__dir__', <built-in method __dir__ of TestClass object at 0x112940978>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of TestClass object at 0x112940978>), ('__format__', <built-in method __format__ of TestClass object at 0x112940978>), ('__ge__', <method-wrapper '__ge__' of TestClass object at 0x112940978>), ('__getattribute__', <method-wrapper '__getattribute__' of TestClass object at 0x112940978>), ('__gt__', <method-wrapper '__gt__' of TestClass object at 0x112940978>), ('__hash__', <method-wrapper '__hash__' of TestClass object at 0x112940978>), ('__init__', <bound method TestClass.__init__ of <__main__.TestClass object at 0x112940978>>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x7f98c185c1c8>), ('__le__', <method-wrapper '__le__' of TestClass object at 0x112940978>), ('__lt__', <method-wrapper '__lt__' of TestClass object at 0x112940978>), ('__module__', '__main__'), ('__ne__', <method-wrapper '__ne__' of TestClass object at 0x112940978>), ('__new__', <built-in method __new__ of type object at 0x10dff55e8>), ('__reduce__', <built-in method __reduce__ of TestClass object at 0x112940978>), ('__reduce_ex__', <built-in method __reduce_ex__ of TestClass object at 0x112940978>), ('__repr__', <method-wrapper '__repr__' of TestClass object at 0x112940978>), ('__setattr__', <method-wrapper '__setattr__' of TestClass object at 0x112940978>), ('__sizeof__', <built-in method __sizeof__ of TestClass object at 0x112940978>), ('__str__', <method-wrapper '__str__' of TestClass object at 0x112940978>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x7f98c185c1c8>), ('__weakref__', None), ('a', 1), ('add', <bound method TestClass.add of <__main__.TestClass object at 0x112940978>>), ('b', 2)]