python学习第四天回顾(生成器,内置函数,yield表达式形式)
| 一、生成器 |
生成器函数:只要函数体包含yield关键字,该函数就是生成器函数
生成器就是迭代器
1 def foo(): #此为非生成器的函数示例 2 return 1 3 return 2 4 return 3 5 return 4 6 7 res1=foo() 8 print(res1) #return只能返回函数中的一个值
1 返回结果为: 2 1
1 def foo(): #此为生成器的示例 2 print('first') 3 yield 1 4 print('second') 5 yield 2 6 print('third') 7 yield 3 8 print('fourth') 9 yield 4 10 print('fifth') 11 #包含yield关键字,即为生成器函数 12 g=foo() #生成器对象foo的内存地址 13 for i in g: #遍历foo的内存地址的内容 14 print(i)
1 返回结果为: #yield一次返回一个值 2 first 3 1 4 second 5 2 6 third 7 3 8 fourth 9 4 10 fifth
1 print(g) #生成器即迭代器 2 3 print(next(g)) #触发迭代器g的执行,进而触发函数的执行 4 print(next(g)) 5 print(next(g)) 6 print(next(g)) 7 print(next(g))
1 计数器小程序示例: 2 def counter(n): 3 print('start...') 4 i=0 5 while i < n: 6 yield i 7 i+=1 8 print('end...') 9 10 11 g=counter(5) 12 for i in g: 13 print(i)
1 返回结果为: 2 start... 3 0 4 1 5 2 6 3 7 4 8 end...
yield的功能:
1、相当于为函数封装好__iter__和__next__
2、return只能返回一次值,函数就终止了,而
yield能返回多次值,每次返回都会将函数暂停,下一次next会从上一次暂停的位置继续执行
模仿tail -f a.txt|grep python小程序:
1 #tail -f a.txt | grep 'python' 2 3 import time #导入time函数 4 def tail(filepath): #定义一下tail函数,设置形参为filepath用于获取文件名 5 with open(filepath,encoding='utf-8') as f: #打开文件 6 f.seek(0,2) #将光标定位到最后 7 while True: 8 line=f.readline().strip() #读取文件中的一行,并去除空格 9 if line: #如果有内容则返回该行 10 yield line 11 else: #否则等待0.2秒 12 time.sleep(0.2) 13 14 t=tail('a.txt') #以迭代器的形式赋值给t 15 16 for line in t: #遍历t得到line的值 17 print(line) 18 19 def grep(pattern,lines): #定义一下grep函数进行查找(形参为pattern,lines,对应grep()函数中的实参) 20 for line in lines: 21 if pattern in line: 22 yield line 23 24 g=grep('python',tail('a.txt')) #实参对应grep()的形参,将grep函数返回的值给g 25 print(g) #打印出g的值来 26 27 for i in g: 28 print(i)
| yield表达式形式 |
#协程函数
1 def deco(func): #检测是否被装饰器所调用检测到有@deco,则跳到@deco并获取eater的内存地址,赋值给形参func 2 def wrapper(*args,**kwargs): #定义wrapper函数,检测是不是闭包函数,执行函数体的内容 3 res=func(*args,**kwargs) #执行func()函数,即执行eater(name)函数==》eater('alex'),将eater生成器的内存地址传给res ) 4 next(res) #next()方法执行生成器,即执行eater()函数,跳转到eater(name)函数体内,首先执行打印语句 5 return res #由food=yield返回给res,现在food为空,所以不会返回值,执行下一个操作g.send(),send有传值的功能,所以会把里面的内容,传给food 6 return wrapper 7 8 @deco 9 def eater(name): 10 print('%s ready to eat' %name) #打印 11 food_list=[] #food_list赋值为列表 12 while True: #执行循环 13 food=yield food_list #检测到yield,返回到上一层,return res, yield 后面的food_list为返回值将会返回food_list里的内容 14 food_list.append(food) #执行g.send("猪肉") send有传值功能,将里面的内容传给food并在food_list内做追加,跳转到下一条命令 15 print('%s start to eat %s' %(name,food)) #打印 16 17 18 g=eater('jack') #上面的都是定义的内容,在执行eater("alex")后才是调用 19 print(g) 20 next(g) 21 22 g.send("猪肉“) #send与next一样都会触发函数的从上往下走的功能,并且send还有传值功能 23 g.send("牛肉") 24 g.send("饼干") 25 g.send("馒头") 26 print(g) 27 print(g.send("猪肉“)) #执行g.send("猪肉"),然后打印其返回结果 28 print(g.send("牛肉")) 29 print(g.send("饼干")) 30 print(g.send("馒头"))
1 返回结果为: 2 jack ready to eat 3 jack start to eat 猪肉 4 jack start to eat 牛肉 5 jack start to eat 饼干 6 jack start to eat 馒头 7 jack start to eat 猪肉 8 ['猪肉', '牛肉', '饼干', '馒头', '猪肉'] 9 jack start to eat 牛肉 10 ['猪肉', '牛肉', '饼干', '馒头', '猪肉', '牛肉'] 11 jack start to eat 饼干 12 ['猪肉', '牛肉', '饼干', '馒头', '猪肉', '牛肉', '饼干'] 13 jack start to eat 馒头 14 ['猪肉', '牛肉', '饼干', '馒头', '猪肉', '牛肉', '饼干', '馒头']
#表达式形式的yield的用途
| #grep -rl "python" /root 查看root目录下面的文件是否有包含python的内容,有则把文件打印出来 |
1 os.walk()方法 用于通过在目录树中游走输出在目录中的文件名,向上或向下。 2 walk()语法: 3 os.walk(top,[,topdown=True[,onerror=None[,foolowlinks=False]]]) 4 参数: 5 top -- 根目录下的每一个文件夹(包含它自己),产生3-元组(dirpath,dirnames,filenames)[文件夹路径,文件夹名字,文件名] 6 topdown -- 可选,为True或者没有指定,一个目录的3-元组将比它的任何子文件的3-元组先产生(目录自上而下)。如果topdown为False,一个目录的3-元组将比它的任何子文件夹的3-元组后产生(目录自下而上) 7 onerror -- 可选,是一个函数,它调用时有一个参数,一个OSError实例。报告这错误后,继续walk,或抛出exception终止walk 8 followlinks -- 设置为true,则通过软连接访问目录
1 import os 2 3 def init(func): 4 def wrapper(*args,**kwargs): 5 res=func(*args,**kwargs) 6 next(res) 7 return res 8 return wrapper 9 10 @init 11 def search(target): 12 while True: 13 search_path=yield 14 g=os.walk(search_path) 15 for par_dir,_,files in g: 16 for file in files: 17 file_abs_path=r'%s\%s' %(par_dir,file) 18 # print(file_abs_path) 19 target.send(file_abs_path) 20 21 @init 22 def opener(target): 23 while True: 24 file_abs_path=yield 25 # print('opener func==>',file_abs_path) 26 with open(file_abs_path,encoding='utf-8') as f: 27 target.send((file_abs_path,f)) 28 29 @init 30 def cat(target): 31 while True: 32 file_abs_path,f=yield #(file_abs_path,f) 33 for line in f: 34 tag=target.send((file_abs_path,line)) 35 if tag: 36 break 37 @init 38 def grep(target,pattern): 39 tag=False 40 while True: 41 file_abs_path,line=yield tag 42 tag=False 43 if pattern in line: 44 tag=True 45 target.send(file_abs_path) 46 47 @init 48 def printer(): 49 while True: 50 file_abs_path=yield 51 print(file_abs_path) 52 53 54 55 x=r'F:\python17期\day5\day5\a' 56 57 58 59 g=search(opener(cat(grep(printer(),'python')))) 60 print(g) 61 62 g.send(x) 63
| 二、内置函数 |
1 print(abs(-1)) #取绝对值 2 print(all([1,2,3])) #在可迭代对象中for循环,逐个进行布尔判断,全为真值则为真 3 4 print(all([0,2,3])) #在可迭代对象中for循环,逐个进行布尔判断,全为真则为值,0在布尔中认为是假值, 5 6 print(all('')) #如果为空则返回真值
1 print(any([0,None,'',1])) #有一个为真则为值,1为真,则返回值为真 2 print(any([0,None,''])) #返回false 3 print(any([])) #空返回为false
1 print(bin(3)) #转换为二进制 2 print(hex(17)) #转换为十六进制 3 print(oct(9)) #转换为八进制
1 def func(): #判断是否为可调用对象 2 pass 3 print(callable(func))
1 print(chr(68)) #ASCII转换为字符 2 print(ord('D')) #字符转换为ASCII
1 res=complex(1+2j) #complex返回一个复数 2 print(res.real) 3 print(res.imag)
1 # dict 字典 2 # int 整形 3 # str 字符串 4 # set 集合 5 # list 列表
1 # l=[] 2 # print(dir(l)) #查看一个对象下面的属性 即查看列表l的内置属性或方法
1 print(help(l))#显示列表l的内置属性的用法
1 print(divmod(1000,30)) #可求出商与余数,可用于分布功能
1 cmd='print("你瞅啥")' #eval将字符串的内容取出来,并执行。 2 eval(cmd) 3 dic="{'a':1,'b':2}" 4 d=eval(dic) 5 print(type(d),d['a'])
1 s={1,2} #s=set({1,2}) 定义可变集合 2 # s.add(3) 3 # print(s) 4 5 # s=frozenset({1,2}) # 定义不可变集合
哈希:
1、只要校验的内容一致,那hash得到结果永远一样
2、不可逆
3、只要采用的哈希算法一样,那无论被校验的内容有多长,hash得到的结果长度都一样
1 print(hash("qwerfdsa") 2 print(hash("qwerfdsa")
1 id() 2 x=1 3 y=x 4 print(id(x),id(y)) 5 print(x is y)
1 pow(x,y[,z]) #计算x的y次方,如果z存在,则在对结果进行取模即pow(x,y)%z 2 print(pow(10,2,3) 3 返回结果为: 4 1
1 reversed() 返转函数 2 l=["a",4,2,3] 3 for i in reversed(l): 4 print(i)
1 round(x[,n]) #返回浮点数x的四舍五入值,n表示保留的位数 2 print(round(3.141542653589127134,4)) 3 返回结果为: 4 3.1415 #保留4位,第5位为2所以舍去
1 slice()#切片操作,示例如下: 2 l=['a','b','c','d','e'] 3 print(l[1:4:2]) 4 s=slice(1,4,2) 5 print(l[s])
1 vars() #返回对象object的属性和属性值的字典对象。如果默认不输入参数,就打印当前调用位置的属性和属性值,若有参数,则只打印这个参数相应的属性和属性值 2 #vars()等同于locals()
1 zip()函数#接受任意多个(包括0和1)序列作为参数,返回一个tulpe列表。 2 示例: 3 s='helloo' 4 l=[1,2,3,4,5] 5 6 z=zip(s,l) 7 print(z) 8 for i in z: 9 print(i) 10 #两个序列的函数必须相等,若不相等则只会截取相等的长度
1 __import__()函数 导入函数 2 3 import time 4 5 m=__import__('time') #以字符串的形式导入模块 6 7 # m.sleep(3000)

浙公网安备 33010602011771号