I want a data structure, fixed size LIFO, last in first out. Is it already there?
Edit: Sorry, what I want is LIFO not FIFO.
I checked http://docs.python.org/library/queue.html, it already provides the LIFO, the only thing I want to achieve is automatically drop the oldest one.
Eg) LIFO size 5 with elements: 1 2 3 4 5
After 6 comes in, the 1 should be dropped, becomes:
2 3 4 5 6
How can 开发者_高级运维this be done?
Both collections.deque and queue.Queue support fifo and a max size.
Adaptation for clarification from the documentation:
queue.LifoQueue supports this, but will not pop the last one when the determined maxsize has been reached:
class queue.LifoQueue(maxsize=0)
Constructor for a LIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.
collections.deque will pop the last one as long as maxlen is defined (which is what OP is looking for):
class collections.deque([iterable[, maxlen]])
If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.
精彩评论