python中sorted函数的原理是什么

发布时间:2021-05-14 16:23:16 作者:Leah
来源:亿速云 阅读:263

python中sorted函数的原理是什么?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

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]))

就这么简单我竟做了一下午(打脸)

题目1

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<b的我时候,会自动调用__ln__(a,b)这个函数,因此我们要在类中重新定义__ln(a,b)__函数,自己定义什么时候返回true什么时候返回false。每一种类型都有自己的ln()函数,所以在重新定义的时候里面也可以调用。

python有哪些常用库

python常用的库:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。

关于python中sorted函数的原理是什么问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. Python3 中sorted() 函数的用法
  2. python sorted函数的小练习及解答

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python sorted

上一篇:如何在python中使用subplot函数

下一篇:如何在python中定义和调用函数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》