3.处理文件,用户指定要查找的文件和内容,将文件中包含要查找内容的每一行都输出到屏幕
def func(filename,text): with open(filename,encoding="utf-8") as f: for i in f: if text in i: yield i fil = func("1","wu")
--------------------- for i in fil:
print(i.strip())
---------------------- print(next(fil)) print(next(fil))
=======================
--------------------------------------------------------------------------------------------------------------------------------
def demo(): for i in range(4): yield i g=demo() g1=(i for i in g) g2=(i for i in g1) print(list(g1)) print(list(g2)) #因g1已经将demo取完,所以会输出[]
---------------------------
output
[0, 1, 2, 3]
[]
---------------------------------------------------------------------------------
def test(): for i in range(4): yield i g=test() for n in [1,10]: g=(add(n,i) for i in g) """ 当n=10时,生成器g并没有执行,所以g执行时n=10 """ print(list(g)) """ 开始执行个g,(add(n,i) for i in g)等价于(add(n,i) for i in (add(n,i) for i in text())) (add(n,i) for i in (10,11,12,13)) """
-----------------------------------------------------------------------------------
output
[20, 21, 22, 23]