1.写生成器,从文件中读取内容,再每一行读取的内容前加上 ‘***’之后返回给用户 def func(filename): word = input('输入你想找的内容:') with open(filename,mode='r',encoding='utf-8') as f: for line in f: if word in line: yield line file = input('输入你要查找的文件:') g = func(file) for i in g: print('###'+ i.strip())
2.面试题
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))
[0, 1, 2, 3]
[]
看这个,我觉得例2可能更贴切于生成器,类似于篮子装东西,取完值则不可再取。
例2:
def demo(): for i in range(4): yield i g=demo() g1=(i for i in g) g2=(i for i in g) print(list(g1)) print(list(g2)) [0, 1, 2, 3] []
3面试题:
def add(n,i): return n+i def test(): for i in range(4): yield i g=test() for n in [1,10]: g=(add(n,i) for i in g) print(list(g))
分析:
for n in [1,10]: g=(add(n,i) for i in g) n = 1 g = (add(n,i) for i in g) n = 10 g = (add(n,i) for i in g) n = 1的表达式 g 赋值给了n=10的g的表达式,g = test()==(0,1,2,3)
n = 1的时候,其下面的表达式并没有被执行调用,等print(list(g))的时候开始调用n=10下面的表达式。 n = 10 g = (add(n,i) for i in (add(n,i) for i in g)) g = (add(n,i) for i in (11,12,13,14)) g = (21,22,23,24)