yield 相当于 return,是一个生成器,目前知道的就两点:

  • 返回一个值,并且记住这个返回的位置,下次迭代就从这个位置后开始
  • 值是一次性的,不可以被反复访问,返回一次后便丢失

deque(maxlen=N) 创建一个固定长度的队列。当有新纪录加入而队列已满时会自动移除最老的那条记录,当不指定 maxlen 时,则代表创建一个可变长的队列。

下面的代码对一系列文本做简单的文本匹配操作,当发现又匹配时就输出当前的匹配行以及最后检查到的那一行文本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from 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('somefile.txt') as f:
for line, prevlines in search(f, 'python', 5):
for pline in prevlines:
print(pline, end='')
print(line, end='')
print('-' * 20)

somefile.txt 文件内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a test file.
This is a python test file.
This is a python test file.
This is a python test file.
This is a python test file.
This is a python test file.
This is a python test file.
This is a python test file.

最后的输出结果为:

对于 deque,可以在两端执行添加和弹出操作:

1
2
3
4
5
6
7
8
9
from collections import deque

q = deque()
q.append(1)
q.appendleft(2)
q.append(3)
print(q) # deque([2, 1, 3])
print(q.pop()) # 3
print(q.popleft()) # 2

参考:《Python Cookbook》