Why is python deque initialized using the last maxlen items in an iterable?

StackOverflow https://stackoverflow.com/questions/19723459

  •  02-07-2022
  •  | 
  •  

質問

I was learning how to use deque. Here's what I did:

>>> d = deque([1,2,3,4,5,6], maxlen=3)

I expected that d would contain [1,2,3]. But instead I got:

>>> d
deque([4, 5, 6], maxlen=3)

Isn't this counterintuitive?

役に立ちましたか?

解決

From docs:

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.

So, your code is equivalent to:

>>> from collections import deque
>>> d = deque(maxlen=3)
>>> for i in range(1, 7):
...     d.append(i)
...     print d
...     
deque([1], maxlen=3)
deque([1, 2], maxlen=3)
deque([1, 2, 3], maxlen=3)
deque([2, 3, 4], maxlen=3)
deque([3, 4, 5], maxlen=3)
deque([4, 5, 6], maxlen=3)

他のヒント

The official doc mentioned this clearly:

Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end.

Not at all, from the docs:

"Returns a new deque object initialized left-to-right (using append()) with data from iterable"

I have mainly used deque objects as buffers for the most recent items. So all the users last 100 actions for example.

It is a design decision. It is more practical to keep more recent elements in the queue. The older are just being poped out from the other end.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top