python sorted排序
python sorted排序
sorted函数原型
sorted(data, cmp=None, key=None, reverse=False)
#data为数据
#cmp和key均为比较函数
#reverse为排序方向,True为倒序,False为正序
基本用法
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5] >>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
对于字典,只对key进行排序
sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]
key函数
key函数应该接受一个参数并返回一个用于排序的key值。由于该函数只需要调用一次,因而排序速度较快。
复杂列表
>>> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
如果列表内容是类的话,
>>> class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
>>> student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
]
>>> sorted(student_objects, key=lambda student: student.age) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
字典
>>> student = [ {"name":"xiaoming", "score":60}, {"name":"daxiong", "score":20},
{"name":"maodou", "score":30},
]
>>> student
[{'score': 60, 'name': 'xiaoming'}, {'score': 20, 'name': 'daxiong'}, {'score': 30, 'name': 'maodou'}]
>>> sorted(student, key=lambda d:d["score"])
[{'score': 20, 'name': 'daxiong'}, {'score': 30, 'name': 'maodou'}, {'score': 60, 'name': 'xiaoming'}]
此外,Python提供了operator.itemgetter和attrgetter提高执行速度。
>>> from operator import itemgetter, attrgetter
>>> student = [
("xiaoming",60),
("daxiong", 20),
("maodou", 30}]
>>> sorted(student, key=lambda d:d[1])
[('daxiong', 20), ('maodou', 30), ('xiaoming', 60)]
>>> sorted(student, key=itemgetter(1))
[('daxiong', 20), ('maodou', 30), ('xiaoming', 60)]
operator提供了多个字段的复杂排序。
>>> sorted(student, key=itemgetter(0,1)) #根据第一个字段和第二个字段
[('daxiong', 20), ('maodou', 30), ('xiaoming', 60)]
operator.methodcaller()函数会按照提供的函数来计算排序。
>>> messages = ['critical!!!', 'hurry!', 'standby', 'immediate!!']
>>> sorted(messages, key=methodcaller('count', '!'))
['standby', 'hurry!', 'immediate!!', 'critical!!!']
首先通过count函数对"!"来计算出现次数,然后按照出现次数进行排序。
CMP
cmp参数是Python2.4之前使用的排序方法。
def numeric_compare(x, y):
return x - y
>>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
[1, 2, 3, 4, 5]
>>> def reverse_numeric(x, y):
return y - x
>>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)
[5, 4, 3, 2, 1]
在functools.cmp_to_key函数提供了比较功能
>>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
[5, 4, 3, 2, 1] def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
python sorted排序的更多相关文章
- python sorted排序用法详解
sorted排序 python sorted 排序 1. operator函数在介绍sorted函数之前需要了解一下operator函数. operator函数是python的内置函数,提供了一系列常 ...
- python 字典排序 关于sort()、reversed()、sorted()
一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...
- <转>python字典排序 关于sort()、reversed()、sorted()
一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...
- Python 列表排序方法reverse、sort、sorted操作方法
python语言中的列表排序方法有三个:reverse反转/倒序排序.sort正序排序.sorted可以获取排序后的列表.在更高级列表排序中,后两中方法还可以加入条件参数进行排序. reverse() ...
- python高阶函数——sorted排序算法
python 内置的sorted()函数可以对一个list进行排序: >>> sorted([8,3,8,11,-2]) [-2, 3, 8, 8, 11] 既然说是高阶函数,那么它 ...
- python之排序(sort/sorted)
大家都知道,python排序有内置的排序函数 sort() 和 高阶函数sorted() .但是它们有什么区别呢? 让我们先从这个函数的定义说起: sorted():该函数第一个参数iterable为 ...
- python的sorted排序具体解释
排序.在编程中常常遇到的算法.我也在几篇文章中介绍了一些关于排序的算法. 有的高级语言内置了一些排序函数.本文讲述Python在这方面的工作.供使用python的程序猿们參考,也让没有使用python ...
- Python中自定义类未定义__lt__方法使用sort/sorted排序会怎么处理?
在<第8.23节 Python中使用sort/sorted排序与"富比较"方法的关系分析>中介绍了排序方法sort和函数sorted在没有提供key参数的情况下默认调用 ...
- python中的sort、sorted排序
我们通常会遇到对数据库中的数据进行排序的问题,今天学习一下对列表和字典的排序方法. 列表 第一种:内建方法sort sort()对列表排序是永久性的排序. 用法:sort(*, key=None, r ...
随机推荐
- java开发常用工具
1.eclipse3.6 +浏览器插件+findbug+checkstyle+pmd+svn 2.plsql8.0对数据库的操作,存储过程的调试 3.Securecrt对linux服务器的操作 4.e ...
- OD使用教程7
破解程序获得使用权限: 破解思路:其实程序加密或者添加neg窗口都是为了让消费者付出更多的代价来解决这些问题.然而身为一个技术人员是可以靠技术来使这些东西消失的.只要我们找到那些东西出现的 ...
- Unity加载模块深度解析(Shader)
作者:张鑫链接:https://zhuanlan.zhihu.com/p/21949663来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 接上一篇 加载模块深度解析(二 ...
- C语言小练习三
题目要求: 定义一个二维数组保存 10个学生的5门课成绩,分别用函数实现:(1)input():输入每个学生的成绩:(2)output():输出每个学生的成绩:(3)aver_stu():计算并输出每 ...
- Services (服务)
*/ .hljs { display: block; padding: 0.5em; background: #F0F0F0; } .hljs, .hljs-subst, .hljs-tag .hlj ...
- [LeetCode] 452 Minimum Number of Arrows to Burst Balloons
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...
- ok
第一个姑娘该是个爱你的人,出现在你没法区分爱和饥渴的时候.那时候你还在青春期的尾巴上,满脑子的性冲动混合着韩剧爱情幻想.你自尊脆弱而又怯懦无助,随便抓住哪一根稻草都当是救命的灵药. 她也许相貌平平,但 ...
- C#学习之Stream
上节课老师主要讲了stream及其一些运用和实例,下面我们就来讨论讨论Stream. 我们知道,C#中常用的stream有文件流(FileSteam),内存流(MemoryStream),压缩流(GZ ...
- mysql 服务windows安装
找到mysql的bin目录,下面有一个mysqld.exe程序,这是用来启动mysql服务的,直接运行即可启动. 还有安装windows服务方式: mysqld.exe -install -manua ...
- springMVC注解启用及优化
使用注解的原因 最方便的还是启用注解 注解方便,而且项目中很流行. 配置文件尽量减少,主要使用注解方式. Springmvc的注解是在2.5版本后有了注解,如何开启注解配置文件 Web.xml文件中不 ...