Python论坛  - 讨论区

标题:Python Cookbook 之 使用deque实现FIFO过滤器

2014年03月03日 星期一 10:04

Python的collections下有着各种各样丰富的数据结构,比如deque,它可以指定固定的容量,当容量用满之后,deque会自动将旧数据剔除除去,从而实现了FIFO的特性。

官方文档有如下解释:

Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

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.

代码示例如下:

from collections import deque

dq=deque(maxlen=5)
for i in range(1,100):
    dq.append(i)

print(dq)

for od in dq:
    print(od,end=" ")

参考资料:

http://docs.python.org/3/library/collections.html#collections.deque

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号