#x=yield 返回值 def l(name): print('loky%s准备吃东西'%name) while True: x=yield None print('loky%s吃了%s'%(name,x)) a=l('1') # print(a) # res=next(a) # print(res) a.send(None)#等同于next(a) a.send(123) a.send('鸡肉') next(a)#None返回 a.close()#关闭之后无法传值,不能穿两个值,但是可以传列表,之后解压赋值,但这不是yield的用处了 a.send(1123)
#三元表达式
#针对一下需求 # def func(x,y): # if x>y: # return x # else: # return y # # res=func(1,2) # print(res) #三元表达式 #语法格式:条件成立是要返回的值 if 条件 else 条件不成立要返回的值 x=1 y=2 res=x if x>y else y print(res)
#生成式
#列表生成是式 l=['loky_1','luce_1','doky'] # new_l=[] # for i in l: # if i.endswith('1'): # new_l.append(i) # print(new_l) # new_l=[i for i in l if i.endswith('1')] # print(new_l) #把所有的小写变成大写 # new_l=[i.upper()for i in l] # print(new_l) #把所有名字去掉后缀_1 # new_l=[i.replace('_1','') for i in l] # print(new_l) #2、字典生成式 # keys=['name','age','gender'] # # dic={key:None for key in keys} # print(dic) # items=[('name','loky'),('age',18),('sex','female')] # # dic={i:j for i,j in items if i!='sex'} # print(dic) #3、集合生成式 # keys={'name','age','sex'} # res={key for key in keys } # print(res,type(res)) #注意没有元组生成式,因为元组是不可变类型,不可append #4、生成器表达式 # a=(i for i in range(10) if i>3) #注意:此时a一个值也没有! with open('db_user.txt',mode='rt',encoding='utf-8') as f: #方式一: # res = 0 # for i in f: # res+=len(i) # print(res) #方式二: # size_of_file=[len(i) for i in f] # print(size_of_file) # res=sum(size_of_file) # print(res) #方式三:效率最高 res=sum(len(i) for i in f) print(res)