python学习之老男孩python全栈第九期_day014作业
0. 默写
a. 生成器函数
获取移动平均值例子:
1 def init(func): 2 def inner(*args,**kwargs): 3 ret = func(*args,**kwargs) 4 ret.__next__() 5 return ret 6 return inner 7 @init 8 def average(): 9 average = 0 10 count = 0 11 sum = 0 12 while 1: 13 num = yield average 14 sum += num 15 count += 1 16 average = sum/count 17 ret = average() 18 print(ret.send(10)) 19 print(ret.send(20))
b. 生成器表达式
egg = ('鸡蛋%s'%i for i in range(10)) for i in egg: print(i)
作业
1. 通读迭代器生成器博客,将所有实例都敲一次,务必把代码的执行过程搞明白
2. 处理文件:用户指定要查找的文件和内容
将文件中包含要查找内容的每一行都输出到屏幕
1 def check_file(): 2 with open('a.txt',encoding='utf-8') as f: 3 for i in f: 4 if 'KID' in i: 5 yield i 6 g = check_file() 7 for i in g: 8 print(i)
3. 写生成器,从文件中读取内容,在每一次读取到的内容之前加上‘***’之后再返回用户
1 def read_file(): 2 with open('a.txt',encoding='utf-8') as f: 3 for i in f: 4 yield '***' + i 5 r = read_file() 6 for i in r: 7 print(i)
推导式练习题:
1. 过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母
1 li = ['qwer','asdf','zxcv','ty','gh','bn','uIo','UIj','plm'] 2 lis = [i.upper() for i in li if len(i) >= 3] 3 print(lis)
2. 求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表
lis = [(x,y) for x in range(0,6,2) for y in range(1,6,2)] print(lis)
3. 求M中3,6,9组成的列表M = [[1,2,3],[4,5,6],[7,8,9]]
M = [[1,2,3],[4,5,6],[7,8,9]] lis = [i[2] for i in M] print(lis)