python sorted函数的小练习及解答
2019-09-18 14:49
1286 查看
前两天学习了一下socket编程,在向某大神请教问题时被嫌弃了,有一种还没学会走就想跑的感觉。大神说我现在的水平应该去做一些像是操作文件、序列号等的小练习来加深理解。下面是他给我出的小练习:
1、datas = [['sherry',19,'female'],['flora',21,'female'],['june',15,'femal']],分别根据名字首字母和年龄进行排序输出;
2、按照给定的输出方式进行输出比较结果,对Person类进行补充;
class_mates = {'sherry':[18,'male'],'june':[20,'female'],'flora':[19,'female'],'alina':[21,'male']} class Person(object): def __init__(self,name,age): self.name = name p1 = Person('sherry',20) p2 = Person('june',20) if p1<p2: print('p1:{} less than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age])) else: print('p1:{} gte than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age]))
就这么简单我竟做了一下午(打脸)
题目
def get_first(info): first_value = info[0][0] return first_value na = sorted(datas,key=get_first) print(na) def age_sort(info): return info[1] print(sorted(datas,key=age_sort))
答案
class_mates = {'sherry':[18,'male'],'june':[20,'female'],'flora':[19,'female'],'alina':[21,'male']} class Person(object): def __init__(self,name,age): self.name = name self.age = age def __lt__(self,others): if(self.age<others.age): return 1 elif(self.age==others.age): if(self.name[0]<others.name[0]): return 1 else: return 0 return 0 p1 = Person('sherry',20) p2 = Person('june',20) if p1<p2: print('p1:{} less than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age])) else: print('p1:{} gte than p2:{}'.format([p1.name,p1.age],[p2.name,p2.age]))
查看python官方文档,总结一下get到的知识。
1、sorted(iterable[, key][, reverse])
返回一个重新排序的list,有两个可选的关键字参数(使用参数名而不是位置来指定参数)。
key 定义了一个带参数的函数,提取list的某个元素作为这个函数的参数,返回值作为你叫关键字,默认值是None(直接比较list的元素)
reverse是一个布尔值。True表示将list里面的元素反向排序。
2、ln(a,b),当使用a<b的我时候,会自动调用__ln__(a,b)这个函数,因此我们要在类中重新定义__ln(a,b)__函数,自己定义什么时候返回true什么时候返回false。每一种类型都有自己的ln()函数,所以在重新定义的时候里面也可以调用。
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- python sorted函数的小练习
- Python_练习实例_(1)计算天数
- Python每天练习——小程序007
- 【Python】Learn Python the hard way, ex41 面向对象术语练习
- PAT乙级题 1079 python解答
- Python基础练习之批量修改文件名
- 深入解答关于Python的11道基本面试题
- 【原创】DE2 实验练习解答—lab 2:数字和显示(digital Logic)(DE2)
- python基础练习:用户登录实验源码
- python的登录验证练习
- 古典概型题目 python练习
- python练习笔记——面试题 F(n) = F(n-1)+F(n-2)
- Python语法基础练习
- python练习之通过python pexpect实现自动生成openssl证书
- Python练习 Chapter 2
- python文件IO,练习运用os.path.exists().
- Python每日一编程小练习(2019.06.10)——赛场统分
- Python核心编程 练习 第五章
- Python 练习实例38
- Python字典小练习