您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

关于python sorted函数的小实例

2024/11/8 3:02:34发布231次查看
前两天学习了一下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))
题目2答案
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 以上就是关于python sorted函数的小实例的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product