《 python3-cookbook 》第一章第三节:保留最后 N 个元素
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, precious_lines
previous_lines.append(line)
# Example use on a file
if __name__ == '__main__':
with open(r'../../somefile.txt') as f:
for line, preclines in search(f, 'python', 5):
for pline in prevlines:
print(pline, end='')
print(line, end='')
print('-' * 20)
代码运行没报错,但是为什么没有 print 出东西?
我调试了一下,好像是search
函数里yield
后面的变量没有返回给line
和preclines
迭代,搞不懂为什么,是我理解错了吗?
1
chenstack 2019-08-08 14:50:23 +08:00
贴出的代码有两处拼写错误
precious_lines -> previous_lines preclines ->prevlines 改完后运行是 ok 的 somefile.txt: java python3 rust php js c++ c go python3.7 ruby output: java python3 -------------------- php python3.7 -------------------- js python3.7 -------------------- c++ python3.7 -------------------- c python3.7 -------------------- go python3.7 -------------------- |
2
scp404 OP 我的错...代码贴错了
直接 copy 书里的源码是这样的 ``` 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(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) ``` 没打印出东西 我是不是回复不了图片。。。 |