问题:

   你想要在迭代或者其他过程中保持一个关于最后几个元素的历史记录。

解决:

   用collections的deque来实现保持一个有限的历史记录是一个绝佳的选择。比如,接下来的代码展现了一个简单的带有前N项匹配记录的文本匹配。

#coding=utf-8from collections import dequedef search(lines, pattern, history=5):    previous_lines = deque(maxlen=history)    for line in lines:        if pattern in line:            yield line, previous_lines        previous_lines.append(line)if __name__ == '__main__':    with open('D:/java.txt') as f:        for line, prevlines in search(f, 'python', 5):            for pline in prevlines:                print(pline, end='')            print(line, end='')            print('-'*20)

讨论:

   编码搜索元素时,像例子中一样使用生成器是很常见的。如果生成器对你很陌生,可以看看 ‘菜谱’4.3。

使用deque方法创建了一个固定长度的队列。当新的元素加入时,如果队列已满,最旧的元素会被自动移除。

>>> q = deque(maxlen=3)>>> q.append(1)>>> q.append(2)>>> q.append(3)>>> qdeque([1, 2, 3], maxlen=3)>>> q.append(4)>>> qdeque([2, 3, 4], maxlen=3)>>> q.append(5)>>> qdeque([3, 4, 5], maxlen=3)>>>

虽然你可以手动使用列表,但是 用上述的方法更优雅,性能也更优。

一般来说,deque方法 也能在你需要队列时使用。如果,你不设定最大长度限制,你会得到一个无长度限制的队列已供你调教~

>>> q = deque()>>> q.append(1)>>> q.append(2)>>> q.append(3)>>> qdeque([1, 2, 3])>>> q.append(4)>>> q.appendleft(5)>>> qdeque([5, 1, 2, 3, 4])>>> q.pop()4>>> qdeque([5, 1, 2, 3])>>> q.popleft()5>>> qdeque([1, 2, 3])

有空把这个也翻了。-。-