当前位置: 首页 > 后端技术 > Python

Python格式化、集合类型和类基础知识练习

时间:2023-03-26 15:43:09 Python

原文:CallmeZhanDodge出处:想想吧链接:https://segmentfault.com/a/11...1.输出%占位符lastname='hello'firstname='world'print('我的名字是%s%s'%(lastname,firstname))2.常用格式化字符%c字符%s由str格式化%i有符号十进制整数%d有符号十进制整数%u无符号十进制整数%o八进制整数%x十六进制整数(小写letter)%eIndexsymbol(小写e)%EIndexsymbol(大写E)%f浮点实数%gShorthandfor%fand%e%G%fand%EShorthand3otherwaysofformattingformatname='OldMaster'age=28print('name:{},age{}'.format(name,age))name:OldMaster,age284.匿名函数lambda参数1,参数2,参数3:表达式特征:1.使用lambda关键字创建函数2.没有名字的函数3.匿名函数在冒号后只有一个表达式,是表达式而不是语句4.自带return5.lambdaExample1defcomputer(x,y):#计算两个数并返回x+yM=lambdax,y:x+yprint(M(1,2))6.lambdaexample1result=lambdaa,b,c:a*b*cprint(result(12,121,1))7lambda三元表达式模拟age=15print('可以参军'ifage>18else'继续上学')#直接调用result=(lambdax,y:x如果x>y否则y)(2,5)8。Recursivefunction#factorialfunctiondeffactorial(n):ifn==1:return1else:returnn*factorial(n-1)passprint(factorial(3))9递归case模拟树结构的遍历importos#文件操作模块deffindFile(file_path):listRs=os.listdir(file_path)#获取fileItemin路径下的所有文件夹listRs:full_path=os.path.join(file_path,fileItem)ifos.path.isdir(full_path):#判断是否为文件夹findFile(full_path)else:print(fileItem)passpasselse:returnfindFile('F:\\7.代码学习')10.Python内置函数abs(-27)#绝对值round(21.1123)#浮点数逼近pow(2,3)#幂2**3divmod(10,3)#业务max(1,2,3,4)#最大值min(1,2,3,4)#最小值sum(1,2,3,4)#求和eval()#动态执行表达式11.类型转换函数int#整数类型float#浮点类型str#字符类型ord#返回对应字符的ASCIIchr#数字到字符ASCIIbool#booleanbin#转换二进制hex#转换为十六进制oct#Octallist#元组转listtuple#元组dict#创建字典bytes#转换为byte12.iterableparameterall#all用于判断给定的iterable参数中的所有元素是否为TRUE,如果为TRUE则返回FALSE,except0,empty,False为TRUEdefall(iterable):foreleiniterable:ifnotele:returnFalsereturnTrueli=[1,2,3,4,5,6,False]print(all(li))#False12iterable参数any#全为false,returnfalsedef任何(可迭代):foreleiniterable:ifele:returnFalsereturnTrueli=[0,False,'']print(any(li))#False13.enumeratelist遍历数据和下标li=['a','b','c']forindex,iteminenumerate(li,7):print(index,item)#将下标改为7a8b9c14.setsetnot支持索引和切片,无序不重复1.创建集合1set1={'1','2'}set2={'11','1'}#addaddset1.add('3')#emptyclear()set1.clear()#取差集differenceset1.difference(set2)#set1取set1中的内容#取交集set1.intersection(set2)#取并集set1.union(set2)set1|set2#去掉最后的set1。pop()#指定去掉set1.discard(3)#updateupdate合并在一起去重set1.update(set2)15Exercise1三组数据之和#1-10,20-30,35-40defthreeSum(a1,a2,a3):返回总和(a1+a2+a3)a1=list(range(1,11))a2=list(range(20,31))a3=list(range(35,41))print(threeSum(a1,a2,a3))16习题2大小和尚有多少defcomputers():foriinrange(1,101):forjinrange(1,34):ifi+j==100and3*j+i/3==100:print('大和尚有{},小和尚有{}'.format(j,i))passcomputers()#大和尚25个,小和尚75个17练习3查找唯一数据li=[1,1,1,2,2,2,2,3,2,2,3,4,2,1,1]deffindUnionNumber(li):foriteminli:如果li.count(item)==1:返回itempassprint(findUnionNumber(li))1.字典统计每个元素出现的次数dict={}forkeyinli:dict[key]=dict.get(key,0)+1print(dict)2.Counter类统计下collection包fromcollectionsimportCountera=[1,2,3,1,1,2]result=Counter(a)print(result)3.pandas包下的value_counts方法统计importpandasaspda=pd.DataFrame([[1,2,3],[3,1,3],[1,2,1]])result=a.apply(pd.value_counts)print(result)18.使用set查找唯一数据li=[1,2,3,3,2,3,4,4,5,1,2,1]defuniqueNum(li):set1=set(li)foriinset1:li.remove(i)set2=set(li)forjinset2:set1.remove(j)returnset1print(uniqueNum(li))'zhan',age=20,defeat(self):print('eating')#创建对象people=People()people.eat()20类内部,使用def定义作为实例方法,第一个参数为self,实例方法归实例所有21添加实例属性classPeople:name='zhan',age=20,defeat(self):print('eating')#创建对象people=People()people.eat()#添加属性people.name2='zhan'people.age2=2222.类classPeople的__init__()方法:#初始化操作,实例属性,自动执行def__init__(self):self.name='zhan'self.age=20defeat(self):print('We'reeating')#创建对象people=People()people.eat()23.类的__init__()使用参数类People:#初始化操作,实例属性,自动执行def__init__(self,name,age):self.name=nameself.age=agedefeat(self,food):print(self.name+food)#createobjectpeople=People('叫我战隐',20)people.eat('iseat')people.eat('bathing')people.eat('running')24理解类self#js中类似Person这个类:defeat(self):print(id(self))passpassperson=Person()person.eat()print(id(person))#self和对象指向同样的内存地址,self是对象的引用#<__main__.Person对象在0x0000020864815CC0>25魔法方法__init__:初始化实例属性__str__:自定义对象的格式__new__:对象实例化__class____del__classAnimal:def__str__(self):return'3213213123123'passanimal=Animal()print(animal)classAnimal:def__str__(self):return'3213213123123'passpassdef__new__(cls,*args,**kwargs):print("----newexecution---")returnobject.__new__(cls)#实际创建对象实例的passanimal=Animal()print(animal)#__new__和__init__的区别__new__类的实例化方法必须返回一个实例,否则会创建失败。初始化__init__数据属性被认为是实例的构造方法,接受self的实例化,构造__new__至少有一个参数是cls,代表要实例化的类。__new__比__init__早执行26)刺刀,掉10滴血#kanren()砍刀,掉15滴血#chiyao()补血10滴血#__str__打印玩家类的状态作用:def__init__(self,name,blood):self.name=nameself.blood=bloodpass#砍人deftong(self,enemy):enemy.blood-=10info='[%s]刺伤[%s]once'%(self.name,enemy.name)print(info)pass#敲人defkanren(self,enemy):enemy.blood-=15info='【%s】砍【%s】一刀'%(self.name,enemy.name)print(info)pass#吃药defchiyao(self):self.blood+=10info='[%s]喝了一口药,增加了10滴血'%(self.name)打印(信息)passdef__str__(self):return'%sstillhas%s'bloodremaining'%(self.name,self.blood)xmcx=Role('XimenChuuxue',100)ygc=Role('YeGucheng',100)whileTrue:ifxmcx.blood<=0orygc.blood<=0:breakprint('********************')xmcx.tong(ygc)xmcx.kanren(ygc)print('**********************')ygc.tong(xmcx)ygc.chiyao()print('**********************')print(xmcx)print(ygc)*********************[XimenChuuxue]stabbed[YeGucheng]withaknife[XimenChuuxue]chopped[YeGucheng]withaknife***********************【YeGucheng]stabbed[XimenChuuxue]Oneknife[YeGucheng]Aftertakingasipofmedicine,10dropsofbloodincreased*********************XimenChuuxuestillhas50HPremainingYeGucheng还剩下25的血量*********************【西门吹雪】捅了【叶孤城】一刀【西门吹雪】砍了【叶孤城】一刀*********************[YeGucheng]stabbed[XimenFuxue][YeGucheng]tookasipofmedicine,increasing10dropsofblood********************XimenFuxuestillhas40HPleftandYeGuchengstillhas10HPleft*********************[XimenChuuxue]stabbed[YeGucheng]withaknife[XimenChuuxue]chopped[YeGucheng]withaknife***************************************************************************************************Gucheng]Stabbed[XimenChuuxue][YeGucheng]tookamouthfulofmedicineandincreased10dropsofblood********************XimenChuuxuestillhas30leftBloodvolumeYeGuchenghas-5bloodvolumeleft27Exampleexercise1FruitclassFruit:def__init__(self,name,color):self.name=nameself.color=colordefshowColor(self):print('%scoloris%s'%(self.name,self.color))apple=Fruit('apple','red').showColor()orange=Fruit('orange','yellow').showColor()watermelen=Fruit('watermelon','green').showColor()28验证self是实例本身classCkeckSelf:def__str__(self):print(id(self))passCkeckSelf().__str__()selfObj=CkeckSelf()print(id(selfObj))29定义动物类并输出所有属性classAnimal:def__init__(self,color,name,age):self.color=colorself.name=名称self.age=agedefrun(self):print('%sisrunning'%(self.name))passdefeat(self):print('%siseating'%(self.name))passdef__str__(self):return'%sof%saged%s'%(self.age,self.color,self.name)cat=Animal('black','kitten',2)dog=Animal('white','puppy',3)cat.run()dog.run()print(cat)print(dog)#小猫在走#小狗在走#2岁黑猫#A3岁-老白狗原文:叫我战隐来源:思想链接:https://segmentfault.com/a/11...