python生成器和yield关键字怎么用

python生成器和yield关键字怎么用

这篇文章主要介绍了python生成器和yield关键字怎么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

下列代码用于先体验普通列表推导式和生成器的差别:

#defadd():#temp=["姓名","学号","班级","电话"]#dic={}#lst=[]#foritemintemp:#inp=input("请输入{}:".format(item))#ifinp=="exit":#print("成功退出输入")#returnFalse#else:#dic[item]=inp#lst.append(dic)#print("添加成功")#returnlst##defshow(lst):#print("-"*30)#print("姓名\t\t学号\t\t班级\t\t电话")#print("="*30)#foriinrange(len(lst)):#forvalinlst[i].values():#print(val,"\t",end="")#print()#print("-"*30)##defsearch(total_lst):#name=input("请输入您要查询的学生姓名:")#flag=False#tmp=[]#foriinrange(len(total_lst)):#iftotal_lst[i]["姓名"]==name:#tmp.append(total_lst[i])#show(tmp)#flag=True#ifnotflag:#print("抱歉,没有找到该学生")##if__name__=='__main__':#total_lst=[]#whileTrue:#flag=add()#ifflag:#total_lst=total_lst+flag#else:#break#show(total_lst)#search(total_lst)##defshow(lst):#print("="*30)#print("{:^25s}".format("输出F1赛事车手积分榜"))#print("="*30)#print("{:<10s}".format("排名"),"{:<10s}".format("车手"),"{:<10s}".format("积分"))#foriinrange(len(lst)):#print("{:0>2d}{:<9s}".format(i+1,""),"{:<10s}".format(lst[i][0]),"{:<10d}".format(lst[i][1]))##if__name__=='__main__':#data='lisi380,jack256,bob385,rose204,alex212'#data=data.split(",")#dic={}#da=[]#foriinrange(len(data)):#da.append(data[i].split())#foriinrange(len(da)):#dic[da[i][0]]=int(da[i][1])#data2=sorted(dic.items(),key=lambdakv:(kv[1],kv[0]),reverse=True)#show(data2)#classFun:#def__init__(self):#print("Fun:__init__()")#deftest(self):#print("Fun")##classInheritFun(Fun):#def__init__(self):#print("InheritedFun.__init__()")#super().__init__()#deftest(self):#super().test()#print("InheritedFun")#a=InheritFun()#a.test()#frommathimport*#classCircle:#def__init__(self,radius=1):#self.radius=radius#defgetPerimeter(self):#return2*self.radius*pi#defgetArea(self):#returnself.radius*self.radius*pi#defsetRadius(self,radius):#self.radius=radius##a=Circle(10)#print("{:.1f},{:.2f}".format(a.getPerimeter(),a.getArea()))#frommathimport*#classRoot:#def__init__(self,a,b,c):#self.a=a#self.b=b#self.c=c#defgetDiscriminant(self):#returnpow(self.b,2)-4*self.a*self.c#defgetRoot1(self):#return(-self.b+pow(pow(self.b,2)-4*self.a*self.c,0.5))/(2*self.a)#defgetRoot2(self):#return(-self.b-pow(pow(self.b,2)-4*self.a*self.c,0.5))/(2*self.a)#inp=input("请输入a,b,c:").split("")#inp=list(map(int,inp))#Root=Root(inp[0],inp[1],inp[2])#print("判别式为:{:.1f};x1:{:.1f};x2:{:.1f}".format(Root.getDiscriminant(),Root.getRoot1(),Root.getRoot2()))#classStock:#def__init__(self,num,name,pre_price,now_price):#self.num=num#self.name=name#self.pre_price=pre_price#self.now_price=now_price#defgetCode(self):#returnself.num#defgetName(self):#returnself.name#defgetPriceYesterday(self):#returnself.pre_price#defgetPriceToday(self):#returnself.now_price#defgetChangePercent(self):#return(self.now_price-self.pre_price)/self.pre_price##sCode=input()#输入代码#sName=input()#输入名称#priceYesterday=float(input())#输入昨日价格#priceToday=float(input())#输入今日价格#s=Stock(sCode,sName,priceYesterday,priceToday)#print("代码:",s.getCode())#print("名称:",s.getName())#print("昨日价格:%.2f\n今天价格:%.2f"%(s.getPriceYesterday(),s.getPriceToday()))#print("价格变化百分比:%.2f%%"%(s.getChangePercent()*100))#frommathimportpi##classShape:#def__init__(self,name='None',area=None,perimeter=None):#self.name=name#self.area=area#self.perimeter=perimeter#defcalArea(self):#returnself.area#defcalPerimeter(self):#returnself.perimeter#defdisplay(self):#print("名称:%s面积:%.2f周长:%.2f"%(self.name,self.area,self.perimeter))##classRectangle(Shape):#def__init__(self,width,height):#super().__init__()#self.width=width#self.height=height#defcalArea(self):#self.area=self.height*self.width#returnself.area#defcalPerimeter(self):#self.perimeter=(self.height+self.width)*2#returnself.perimeter#defdisplay(self):#self.name="Rectangle"#Rectangle.calArea(self)#Rectangle.calPerimeter(self)#super(Rectangle,self).display()##classTriangle(Shape):#def__init__(self,bottom,height,edge1,edge2):#super().__init__()#self.bottom=bottom#self.height=height#self.edge1=edge1#self.edge2=edge2#defcalArea(self):#self.area=(self.bottom*self.height)/2#returnself.area#defcalPerimeter(self):#self.perimeter=self.bottom+self.edge2+self.edge1#returnself.perimeter#defdisplay(self):#self.name="Triangle"#Triangle.calArea(self)#Triangle.calPerimeter(self)#super(Triangle,self).display()##classCircle(Shape):#def__init__(self,radius):#super(Circle,self).__init__()#self.radius=radius#defcalArea(self):#self.area=pi*pow(self.radius,2)#returnself.area#defcalPerimeter(self):#self.perimeter=2*pi*self.radius#returnself.perimeter#defdisplay(self):#self.name="Circle"#Circle.calArea(self)#Circle.calPerimeter(self)#super(Circle,self).display()##rectangle=Rectangle(2,3)#rectangle.display()##triangle=Triangle(3,4,4,5)#triangle.display()##circle=Circle(radius=1)#circle.display()##lst=list(map(lambdax:int(x),['1','2','3']))#print(lst)##classListNode(object):#def__init__(self):#self.val=None#self.next=None###尾插法#defcreatlist_tail(lst):#L=ListNode()#头节点#first_node=L#foriteminlst:#p=ListNode()#p.val=item#L.next=p#L=p#returnfirst_node##头插法#defcreatlist_head(lst):#L=ListNode()#头节点#foriteminlst:#p=ListNode()#p.val=item#p.next=L#L=p#returnL##打印linklist#defprint_ll(ll):#whileTrue:#ifll.val:#print(ll.val)#ifll.next==None:#尾插法停止点#break#elifnotll.next:#头插法停止点#break#ll=ll.next##题解#classSolution:#defprintListFromTailToHead(self,listNode):##writecodehere#res=[]#while(listNode):#res.append(listNode.val)#listNode=listNode.next#returnres[3:0:-1]##if__name__=="__main__":#lst=[1,2,3]#linklist=creatlist_tail(lst)#solution=Solution()#res=solution.printListFromTailToHead(linklist)#print(res)#-*-coding:utf-8-*-#classSolution:#def__init__(self):#self.stack1=[]#self.stack2=[]#defpush(self,node):##writecodehere#self.stack1.append(node)#defpop(self):##returnxx#ifself.stack2:#returnself.stack2.pop()#else:#foriinrange(len(self.stack1)):#self.stack2.append(self.stack1.pop())#returnself.stack2.pop()##if__name__=='__main__':#solution=Solution()#solution.push(1)#solution.push(2)#print(solution.pop())#print(solution.pop())##binarysearch#defbinary_search(lst,x):#lst.sort()#iflen(lst)>0:#pivot=len(lst)//2#iflst[pivot]==x:#returnTrue#eliflst[pivot]>x:#returnbinary_search(lst[:pivot],x)#eliflst[pivot]<x:#returnbinary_search(lst[pivot+1:],x)#returnFalse##defbinary_search3(lst,x):#lst.sort()#head=0#tail=len(lst)#pivot=len(lst)//2#whilehead<=tail:#iflst[pivot]>x:#tail=pivot#pivot=(head+tail)//2#eliflst[pivot]<x:#head=pivot#pivot=(head+tail)//2#eliflst[pivot]==x:#returnTrue#returnFalse#if__name__=='__main__':#lst=[5,3,1,8,9]#print(binary_search(lst,3))#print(binary_search(lst,100))##print(binary_search(lst,8))#print(binary_search(lst,100))#括号匹配#defbracket_matching(ans):#stack=[]#flag=True#left=['(','{','[']#right=[')','}',']']#foriinrange(len(ans)):#ifans[i]inleft:#stack.append(ans[i])#else:#tmp=stack.pop()#ifleft.index(tmp)!=right.index(ans[i]):#flag=False#ifstack:#flag=False#returnflag##print(bracket_matching('({})()[[][]'))#print(bracket_matching('({})()[[]]'))#deflongestValidParentheses(s):#maxlen=0#stack=[]#foriinrange(len(s)):#ifs[i]=='(':#stack.append(s[i])#ifs[i]==')'andlen(stack)!=0:#stack.pop()#maxlen+=2#returnmaxlen#print(longestValidParentheses('()(()'))#defGetLongestParentheses(s):#maxlen=0#start=-1#stack=[]#foriinrange(len(s)):#ifs[i]=='(':#stack.append(i)#else:#ifnotstack:#start=i#else:#stack.pop()#ifnotstack:#maxlen=max(maxlen,i-start)#else:#maxlen=max(maxlen,i-stack[-1])#returnmaxlen#print(GetLongestParentheses('()(()'))#print(GetLongestParentheses('()(()))'))#print(GetLongestParentheses(')()())'))#importtorch#a=torch.tensor([[[1,0,3],#[4,6,5]]])#print(a.size())#b=torch.squeeze(a)#print(b,b.size())#b=torch.squeeze(a,-1)#print(b,b.size())#b=torch.unsqueeze(a,2)#print(b,b.size())##print('-----------------')#x=torch.zeros(2,1,2,1,2)#print(x.size())#y=torch.squeeze(x)#print(y.size())#y=torch.squeeze(x,0)#print(y.size())#y=torch.squeeze(x,1)#print(y.size())#fromtypingimportList#classSolution:#defduplicate(self,numbers:List[int])->int:##writecodehere#dic=dict()#foriinrange(len(numbers)):#ifnumbers[i]notindic.keys():#dic[numbers[i]]=1#else:#dic[numbers[i]]+=1#forkey,valueindic.items():#ifvalue>1:#returnkey#return-1#if__name__=='__main__':#solution=Solution()#print(solution.duplicate([2,3,1,0,2,5,3]))#classTreeNode:#def__init__(self,data=0):#self.val=data#self.left=None#self.right=None###classSolution:#defTreeDepth(self,pRoot:TreeNode)->int:##writecodehere#ifpRootisNone:#return0#count=0#now_layer=[pRoot]#next_layer=[]#whilenow_layer:#foriinnow_layer:#ifi.left:#next_layer.append(i.left)#ifi.right:#next_layer.append(i.right)#count+=1#now_layer,next_layer=next_layer,[]#returncount##if__name__=='__main__':#inp=[1,2,3,4,5,'#',6,'#','#',7]#bt=TreeNode(1)##bt.left=TreeNode(2)#bt.right=TreeNode(3)##bt.left.left=TreeNode(4)#bt.left.right=TreeNode(5)#bt.right.left=None#bt.right.right=TreeNode(6)##bt.left.left.left=None#bt.left.left.right=None#bt.left.right.left=TreeNode(7)##solution=Solution()#print('深度:',solution.TreeDepth(bt))#classListNode:#def__init__(self):#self.val=None#self.next=None##defcreatlist_tail(lst):#L=ListNode()#first_node=L#foriteminlst:#p=ListNode()#p.val=item#L.next=p#L=p#returnfirst_node##defshow(node:ListNode):#print(node.val,end='')#ifnode.nextisnotNone:#node=show(node.next)##classSolution:#defReverseList(self,head:ListNode)->ListNode:##writecodehere#res=None#whilehead:#nextnode=head.next#head.next=res#res=head#head=nextnode#returnres##if__name__=='__main__':#lst=[1,2,3]#linklist=creatlist_tail(lst)#show(linklist)#print()#solution=Solution()#show(solution.ReverseList(linklist))#字典推导式#a=['a','b','c']#b=[4,5,6]#dic={k:vfork,vinzip(a,b)}#print(dic)#列表推导式#l=[iforiinrange(10)]#print(l)#####生成器推导式#l1=(iforiinrange(10))#print(type(l1))#输出结果:<class'generator'>#foriinl1:#print(i)#print('{pi:0>10.1f}'.format(pi=3.14159855))#print("'","center".center(40),"'")#print("center".center(40,'-'))#print("center".zfill(40))#print("center".ljust(40,'-'))#print("center".rjust(40,'-'))#s="pythoniseasytolearn,easytouse."#print(s.find('to',0,len(s)))#print(s.find('es'))#num=[1,2,3]#print("+".join(str(i)foriinnum),"=",sum(num))#print(''.center(40,'-'))##importtorch#fromtorchimportnn#importnumpyasnp###一维BN#d1=torch.rand([2,3,4])#BCW#bn1=nn.BatchNorm1d(3,momentum=1)#res=bn1(d1)#print(res.shape)###二维BN(常用)#d2=torch.rand([2,3,4,5])#BCHW#bn2=nn.BatchNorm2d(3,momentum=1)#res=bn2(d2)#print(res.shape)#print(bn2.running_mean)#3个chanel均值#print(bn2.running_var)#3个chanel方差###a=np.array(d2.tolist())#mean=np.mean(a,axis=(0,2,3))#print(mean)###defbatchnorm_forward(x,gamma,beta,bn_param):#"""#Forwardpassforbatchnormalization##Input:#-x:Dataofshape(N,D)#-gamma:Scaleparameterofshape(D,)#-beta:Shiftparameterofshape(D,)#-bn_param:Dictionarywiththefollowingkeys:#-mode:'train'or'test'#-eps:Constantfornumericstability#-momentum:Constantforrunningmean/variance#-running_mean:Arrayofshape(D,)givingrunningmeanoffeatures#-running_varArrayofshape(D,)givingrunningvarianceoffeatures#Returnsatupleof:#-out:ofshape(N,D)#-cache:Atupleofvaluesneededinthebackwardpass#"""#mode=bn_param['mode']#eps=bn_param.get('eps',1e-5)#momentum=bn_param.get('momentum',0.9)##N,D=x.shape#running_mean=bn_param.get('running_mean',np.zeros(D,dtype=x.dtype))#running_var=bn_param.get('running_var',np.zeros(D,dtype=x.dtype))##out,cache=None,None##ifmode=='train':#sample_mean=np.mean(x,axis=0)#np.mean([[1,2],[3,4]])->[2,3]#sample_var=np.var(x,axis=0)#out_=(x-sample_mean)/np.sqrt(sample_var+eps)##running_mean=momentum*running_mean+(1-momentum)*sample_mean#running_var=momentum*running_var+(1-momentum)*sample_var##out=gamma*out_+beta#cache=(out_,x,sample_var,sample_mean,eps,gamma,beta)#elifmode=='test':##scale=gamma/np.sqrt(running_var+eps)##out=x*scale+(beta-running_mean*scale)#x_hat=(x-running_mean)/(np.sqrt(running_var+eps))#out=gamma*x_hat+beta#else:#raiseValueError('Invalidforwardbatchnormmode"%s"'%mode)###Storetheupdatedrunningmeansbackintobn_param#bn_param['running_mean']=running_mean#bn_param['running_var']=running_var##returnout,cache##importnumpyasnp#importmatplotlib.pyplotasplt###defpy_cpu_nms(dets,thresh):##x1=dets[:,0]#y1=dets[:,1]#x2=dets[:,2]#y2=dets[:,3]#scores=dets[:,4]#areas=(x2-x1+1)*(y2-y1+1)#res=[]#index=scores.argsort()[::-1]#whileindex.size>0:#i=index[0]#res.append(i)#x11=np.maximum(x1[i],x1[index[1:]])#y11=np.maximum(y1[i],y1[index[1:]])#x22=np.minimum(x2[i],x2[index[1:]])#y22=np.minimum(y2[i],y2[index[1:]])##w=np.maximum(0,x22-x11+1)#h=np.maximum(0,y22-y11+1)##overlaps=w*h#iou=overlaps/(areas[i]+areas[index[1:]]-overlaps)##idx=np.where(iou<=thresh)[0]#index=index[idx+1]#print(res)#returnres##defplot_boxs(box,c):#x1=box[:,0]#y1=box[:,1]#x2=box[:,2]#y2=box[:,3]##plt.plot([x1,x2],[y1,y1],c)#plt.plot([x1,x2],[y2,y2],c)#plt.plot([x1,x1],[y1,y2],c)#plt.plot([x2,x2],[y1,y2],c)##if__name__=='__main__':#boxes=np.array([[100,100,210,210,0.72],#[250,250,420,420,0.8],#[220,220,320,330,0.92],#[230,240,325,330,0.81],#[220,230,315,340,0.9]])#plt.figure()#ax1=plt.subplot(121)#ax2=plt.subplot(122)#plt.sca(ax1)#plot_boxs(boxes,'k')##res=py_cpu_nms(boxes,0.7)#plt.sca(ax2)#plot_boxs(boxes[res],'r')#plt.show()#2334#123#456#1234#5678#9101112#lst1,lst2=[],[]#n1,m1,n2,m2=map(int,input().split())#foriinrange(n1):#nums=list(map(int,input().split()))#输入一行数据#lst1.append(nums)#foriinrange(n2):#nums=list(map(int,input().split()))#lst2.append(nums)#res=[]#foriinrange(n1):#res.append([])#forjinrange(m2):#lst4=[]#lst3=lst1[i]#forkinrange(n2):#lst4.append(lst2[k][j])#res_num=sum(map(lambdax,y:x*y,lst3,lst4))#res[i].append(res_num)#print(res)##importnumpyasnp#print('numpy:',np.dot(lst1,lst2))#定义残差块#importtorch#importtorch.nnasnn#importtorch.nn.functionalasF##classResBlock(nn.Module):#def__init__(self,inchanel,outchanel,stride=1):#super(ResBlock,self).__init__()#self.left=nn.Sequential(#nn.Conv2d(inchanel,outchanel,kernel_size=3,stride=stride,padding=1,bias=False),#nn.BatchNorm2d(outchanel),#nn.ReLU(inplace=True),#nn.Conv2d(outchanel,outchanel,kernel_size=3,stride=1,padding=1,bias=False),#nn.BatchNorm2d(outchanel)#)#self.shortcut=nn.Sequential()#ifstride!=1orinchanel!=outchanel:#self.shortcut=nn.Sequential(#nn.Conv2d(inchanel,outchanel,kernel_size=1,stride=stride,padding=1,bias=False),#nn.BatchNorm2d(outchanel)#)#defforward(self,x):#out=self.left(x)#out=out+self.shortcut(x)#out=F.relu(out)##returnout##classResNet(nn.Module):#def__init__(self,Resblock,num_classes=10):#super(ResNet,self).__init__()#self.inchanel=64#self.conv1=nn.Sequential(#nn.Conv2d(3,64,kernel_size=3,stride=1,padding=1,bias=False),#nn.BatchNorm2d(64),#nn.ReLU()#)#self.layer1=self.make_layer(ResBlock,64,2,1)#self.layer2=self.make_layer(ResBlock,128,2,2)#self.layer3=self.make_layer(ResBlock,256,2,2)#self.layer4=self.make_layer(ResBlock,512,2,2)#self.fc=nn.Linear(512,num_classes)##defmake_layer(self,ResBlock,channels,num_blocks,stride):#strides=[stride]+[1]*(num_blocks-1)#layers=[]#forstrideinstrides:#layers.append(ResBlock(self.inchanel,channels,stride))#self.inchanel=channels#returnnn.Sequential(*layers)#defforward(self,x):#out=self.conv1(x)#out=self.layer1(out)#out=self.layer2(out)#out=self.layer3(out)#out=self.layer4(out)#out=F.avg_pool2d(out,4)#out=out.view(out.size(0),-1)#out=self.fc(out)#returnout#importtorch#importtorch.nnasnn#importtorch.nn.functionalasF##classASPP(nn.Module):#def__init__(self,in_channel=512,depth=256):#super(ASPP,self).__init__()#self.mean=nn.AdaptiveAvgPool2d((1,1))#self.conv=nn.Conv2d(in_channel,depth,1,1)#self.atrous_block1=nn.Conv2d(in_channel,depth,1,1)#self.atrous_block6=nn.Conv2d(in_channel,depth,3,1,padding=6,dilation=6)#self.atrous_block12=nn.Conv2d(in_channel,depth,3,1,padding=12,dilation=12)#self.atrous_block18=nn.Conv2d(in_channel,depth,3,1,padding=18,dilation=18)#self.conv1x1_output=nn.Conv2d(depth*5,depth,1,1)#defforward(self,x):#size=x[2:]#pool_feat=self.mean(x)#pool_feat=self.conv(pool_feat)#pool_feat=F.upsample(pool_feat,size=size,mode='bilinear')##atrous_block1=self.atrous_block1(x)#atrous_block6=self.atrous_block6(x)#atrous_block12=self.atrous_block12(x)#atrous_block18=self.atrous_block18(x)##out=self.conv1x1_output(torch.cat([pool_feat,atrous_block1,atrous_block6,#atrous_block12,atrous_block18],dim=1))#returnout#牛顿法求三次根#defsqrt(n):#k=n#whileabs(k*k-n)>1e-6:#k=(k+n/k)/2#print(k)##defcube_root(n):#k=n#whileabs(k*k*k-n)>1e-6:#k=k+(k*k*k-n)/3*k*k#print(k)#sqrt(2)#cube_root(8)#-*-coding:utf-8-*-#importrandom##importnumpyasnp#frommatplotlibimportpyplot###classK_Means(object):##k是分组数;tolerance‘中心点误差';max_iter是迭代次数#def__init__(self,k=2,tolerance=0.0001,max_iter=300):#self.k_=k#self.tolerance_=tolerance#self.max_iter_=max_iter##deffit(self,data):#self.centers_={}#foriinrange(self.k_):#self.centers_[i]=data[random.randint(0,len(data))]##print('center',self.centers_)#foriinrange(self.max_iter_):#self.clf_={}#用于装归属到每个类中的点[k,len(data)]#foriinrange(self.k_):#self.clf_[i]=[]##print("质点:",self.centers_)#forfeatureindata:#distances=[]#装中心点到每个点的距离[k]#forcenterinself.centers_:##欧拉距离#distances.append(np.linalg.norm(feature-self.centers_[center]))#classification=distances.index(min(distances))#self.clf_[classification].append(feature)###print("分组情况:",self.clf_)#prev_centers=dict(self.centers_)##forcinself.clf_:#self.centers_[c]=np.average(self.clf_[c],axis=0)###'中心点'是否在误差范围#optimized=True#forcenterinself.centers_:#org_centers=prev_centers[center]#cur_centers=self.centers_[center]#ifnp.sum((cur_centers-org_centers)/org_centers*100.0)>self.tolerance_:#optimized=False#ifoptimized:#break##defpredict(self,p_data):#distances=[np.linalg.norm(p_data-self.centers_[center])forcenterinself.centers_]#index=distances.index(min(distances))#returnindex###if__name__=='__main__':#x=np.array([[1,2],[1.5,1.8],[5,8],[8,8],[1,0.6],[9,11]])#k_means=K_Means(k=2)#k_means.fit(x)#forcenterink_means.centers_:#pyplot.scatter(k_means.centers_[center][0],k_means.centers_[center][1],marker='*',s=150)##forcatink_means.clf_:#forpointink_means.clf_[cat]:#pyplot.scatter(point[0],point[1],c=('r'ifcat==0else'b'))##predict=[[2,1],[6,9]]#forfeatureinpredict:#cat=k_means.predict(feature)#pyplot.scatter(feature[0],feature[1],c=('r'ifcat==0else'b'),marker='x')##pyplot.show()#defpred(key,value):#ifkey=='math':#returnvalue>=40#else:#returnvalue>=60#deffunc(dic,pred):##temp=[]##foritemindic:##ifnotpred(item,dic[item]):##temp.append(item)##foritemintemp:##deldic[item]##returndic##forkinlist(dic.keys()):#ifdic[k]<60:#deldic[k]#returndic##if__name__=='__main__':#dic={'math':66,'c':78,'c++':59,'python':55}#dic=func(dic,pred)#print(dic)##classTreeNode:#def__init__(self):#self.left=None#self.right=None#self.data=None##definsert(tree,x):#temp=TreeNode()#temp.data=x#iftree.data>x:#iftree.left==None:#tree.left=temp#else:#insert(tree.left,x)#else:#iftree.right==None:#tree.right=temp#else:#insert(tree.right,x)##defprint_tree(node):#ifnodeisNone:#return0#print_tree(node.left)#print(node.data)#print_tree(node.right)###defsort(lst):#tree=TreeNode()#tree.data=lst[0]#foriinrange(1,len(lst)):#insert(tree,lst[i])#print_tree(tree)##sort([5,2,4])#fromcollectionsimportIterable,Iterator###classPerson(object):#"""定义一个人类"""##def__init__(self):#self.name=list()#self.name_num=0##defadd(self,name):#self.name.append(name)##def__iter__(self):#returnself#def__next__(self):##记忆性返回数据#ifself.name_num<len(self.name):#ret=self.name[self.name_num]#self.name_num+=1#returnret#else:#raiseStopIteration##person1=Person()#person1.add("张三")#person1.add("李四")#person1.add("王五")##print("判断是否是可迭代的对象:",isinstance(person1,Iterable))#print("判断是否是迭代器:",isinstance(person1,Iterator))#fornameinperson1:#print(name)#nums=[]#a=0#b=1#i=0#whilei<10:#nums.append(a)#a,b=b,a+b#i+=1#foriinnums:#print(i)##classFb():#def__init__(self):#self.a=0#self.b=1#self.i=0#def__iter__(self):#returnself#def__next__(self):#res=self.a#ifself.i<10:#self.a,self.b=self.b,self.a+self.b#self.i+=1#returnres#else:#raiseStopIteration##fb=Fb()#foriinfb:#print(i)importtimedefget_time(func):defwraper(*args,**kwargs):start_time=time.time()result=func(*args,**kwargs)end_time=time.time()print("Spend:",end_time-start_time)returnresultreturnwraper@get_timedef_list(n):l=[i*i*iforiinrange(n)]@get_timedef_generator(n):ge=(i*i*iforiinrange(n))@get_timedef_list_print(l1):foriinl1:print(end='')@get_timedef_ge_print(ge):foriinge:print(end='')n=100000print('list生成耗时:')_list(n)print('生成器生成耗时:')_generator(n)l1=[i*i*iforiinrange(n)]ge=(i*i*iforiinrange(n))#print(l1)#print(ge)print('list遍历耗时:')_list_print(l1)print('生成器遍历耗时:')_ge_print(ge)

结论:

生成速度:生成器>列表
for_in_循环遍历:1、速度方面:列表>生成器;2、内存占用方面:列表<生成器
总的来说,生成器就是用于降低内存消耗的。

感谢你能够认真阅读完这篇文章,希望小编分享的“python生成器和yield关键字怎么用”这篇文章对大家有帮助,同时也希望大家多多支持恰卡编程网,关注恰卡编程网行业资讯频道,更多相关知识等着你来学习!

发布于 2022-01-14 22:35:01
收藏
分享
海报
0 条评论
43
上一篇:C++中vector怎么使用 下一篇:Spring Boot实现热部署的方式有哪些
目录

    推荐阅读

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码