python基础:带有yield关键字函数调用后每一步详解
1 #-*- coding:utf-8 -*- 2 __author__ = 'Administrator' 3 4 from collections import deque 5 6 def search(lines, pattern, history=5): 7 previons_line = deque(maxlen=history) 8 for line in lines: 9 if pattern in line: 10 yield line, previons_line 11 previons_line.append(line) 12 13 14 # Example use on a file 15 if __name__ == '__main__': 16 with open('.\somefile.txt') as f: 17 for line, prevlines in search(f, 'python', 5): 18 for pline in prevlines: 19 print(pline) 20 print(line, "end=''") 21 print('-'*20) 22 23
somefile.txt文件的内容:
第一次调用search()函数运行到yield line,previons_line时就返回到主函数,即previons_line是空的,从而执行主函数后面的输出;第二次调用search()函数,直接从previons_line.append(line)开始运行,直到运行到yield line,previons_line时就返回到主函数。依次类推,所以somefile.txt中最后一行“python is end.”不会加入到previons_line中。