importrandom# 首先创建学生的类classStudent:def__init__(name,age,score,height):# 字段的创建与初始化为了简化代码突出重点知识这里全都采用公有字段。self.name,self.age,self.score,self.heightname,age,score,height# 打印函数def__rper__():return(姓名:%s 年龄:%d 成绩:%d 身高:%d)%(self.name,self.age,self.score,self.height)# 根据名字创建一些学生names[张三,李四,王五,赵六]ls[]fornameinnames:sStudent(name,random.randint(13,17),random.randint(0,100),random.randint(110,190))ls.append(s)# 获得装有学生的列表ls# 编写排序函数defsort(ll,fuction):# ll ls fuction older_than 传参既是赋值foriinrange(len(ll)-1):forjinrange(0,len(ll)-1-i):iffuction(ll[j],ll[j1]):ll[j],ls[j1]ll[j1],ls[j]# 写一个比较两个学生的函数左边的年龄大返回真defolder_than(stu1,stu2):returnstu1.agestu2.age# 写一个比较两个学生的函数右边的年龄大返回真defyounger_than(stu1,stu2):returnstu1.agestu2.age# 写一个比较两个学生的函数左边的成绩差返回真defscore_worse(stu1,stu2):returnstu1.scorestu2.score# 写一个比较两个学生的函数左边的个子小返回真defshorter_than(stu1,stu2):returnstu1.heightstu2.height# 调用排序函数根据的年龄从小到大排序sort(ls,older_than)print(ls)# 调用排序函数根据的年龄从大到小排序sort(ls,younger_than)print(ls)# 调用排序函数根据的成绩从高到低排序sort(ls,score_worse)print(ls)# 调用排序函数根据的身高从高到矮排序sort(ls,shorter_than)print(ls)
一个例子学会python中将函数作为参数
importrandom# 首先创建学生的类classStudent:def__init__(name,age,score,height):# 字段的创建与初始化为了简化代码突出重点知识这里全都采用公有字段。self.name,self.age,self.score,self.heightname,age,score,height# 打印函数def__rper__():return(姓名:%s 年龄:%d 成绩:%d 身高:%d)%(self.name,self.age,self.score,self.height)# 根据名字创建一些学生names[张三,李四,王五,赵六]ls[]fornameinnames:sStudent(name,random.randint(13,17),random.randint(0,100),random.randint(110,190))ls.append(s)# 获得装有学生的列表ls# 编写排序函数defsort(ll,fuction):# ll ls fuction older_than 传参既是赋值foriinrange(len(ll)-1):forjinrange(0,len(ll)-1-i):iffuction(ll[j],ll[j1]):ll[j],ls[j1]ll[j1],ls[j]# 写一个比较两个学生的函数左边的年龄大返回真defolder_than(stu1,stu2):returnstu1.agestu2.age# 写一个比较两个学生的函数右边的年龄大返回真defyounger_than(stu1,stu2):returnstu1.agestu2.age# 写一个比较两个学生的函数左边的成绩差返回真defscore_worse(stu1,stu2):returnstu1.scorestu2.score# 写一个比较两个学生的函数左边的个子小返回真defshorter_than(stu1,stu2):returnstu1.heightstu2.height# 调用排序函数根据的年龄从小到大排序sort(ls,older_than)print(ls)# 调用排序函数根据的年龄从大到小排序sort(ls,younger_than)print(ls)# 调用排序函数根据的成绩从高到低排序sort(ls,score_worse)print(ls)# 调用排序函数根据的身高从高到矮排序sort(ls,shorter_than)print(ls)