保留最后 N 个元素
问题
在迭代操作或者其他操作的时候,怎样只保留最后有限几个元素的历史记录?
实现
保留有限历史记录可通过
collections.deque
实现。例如下面的代码在多行上面做简单的文本匹配, 并返回匹配所在行的最后N行:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17from collections import deque
def 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)
# Example use on a file
if __name__ == '__main__':
with open(r'../../cookbook/somefile.txt') as f:
for line, prevlines in search(f, 'python', 5):
for pline in prevlines:
print(pline, end='')
print(line, end='')
print('-' * 20)
deque 用法简述
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23from collections import deque
语法:
deque([iterable[, maxlen]]) --> deque object
iterable:init iterable
maxlen: maximum size of a deque or None if unbounded
方法:
append(...) Add an element to the right side of the deque.
appendleft(...) Add an element to the left side of the deque.
clear(...) Remove all elements from the deque.
copy(...) Return a shallow copy of a deque.
count(...) D.count(value) -> integer -- return number of occurrences of value
extend(...) Extend the right side of the deque with elements from the iterable
extendleft(...) Extend the left side of the deque with elements from the iterable
index(...) D.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
insert(...) D.insert(index, object) -- insert object before index
pop(...) Remove and return the rightmost element.
popleft(...) Remove and return the leftmost element.
remove(...) D.remove(value) -- remove first occurrence of value.
reverse(...) D.reverse() -- reverse *IN PLACE*
rotate(...) Rotate the deque n steps to the right (default n=1). If n is negative
Reference
https://python3-cookbook.readthedocs.io/zh_CN/latest/c01/p03_keep_last_n_items.html