简体   繁体   English

为什么使用可迭代的最后一个maxlen项初始化python deque?

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

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]. 我期望d将包含[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. 有界长度双端队列提供的功能类似于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" “返回一个新的双端队列对象,它使用可迭代的数据从左到右初始化(使用append())”

I have mainly used deque objects as buffers for the most recent items. 我主要使用双端队列对象作为最新项的缓冲区。 So all the users last 100 actions for example. 例如,所有用户最后执行100次操作。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM