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 ...
随机推荐
- Fuzzy Probability Theory---(3)Discrete Random Variables
We start with the fuzzy binomial. Then we discuss the fuzzy Poisson probability mass function. Fuzzy ...
- ZooKeeper事务日志记录器SyncRequestProcessor
SyncRequestProcessor作为一个ZooKeeper中的一个关键线程(ZooKeeperCriticalThread),是ZooKeeper请求处理链中的事务日志记录处理器,其主要用来将 ...
- android系统启动
首页 资讯 精华 论坛 问答 博客 专栏 群组 更多 ▼ 您还未登录 ! 登录 注册 Ant space 博客 微博 相册 收藏 留言 关于我 android启动过程再研 Androi ...
- JAVA编程心得-Eclipse/MyEclipse 中文乱码解决办法
将别人的项目或JAVA文件导入到自己的Eclipse中时,常常会出现JAVA文件的中文注释变成乱码的情况,主要原因就是别人的IDE编码格式和自己的Eclipse编码格式不同.总结网上的建议和自己的体会 ...
- GridView基础知识
首先,gridview是封装好的,直接在设计界面使用,基本不需要写代码: 1.绑定数据源 GridView最好与LinQDatasourse配合使用,相匹配绑定数据: 2.外观控制 整体控制 自动选择 ...
- 微信小程序 设计理念指南
在此处输入标题 微信小程序的几条开发建议 功能简约,场景贴近随用随走: 操作快捷方便,交互简单: 程序本身代码资源等文件大小限制在1MB之内,这是微信目前的硬限制,目的是为了使得最终到达用户设备上 ...
- 猜字符游戏之java
package days06; //需求......,问题,为什么要用do{}while???import java.util.Scanner;public class RepeatOfGussing ...
- RocksDB笔记 - Compaction中的Iterator
Compaction中的Iterator 一般来说,Compaction的Input涉及两层数据的合并,对于涉及到的每一层数据: 如果是level-0,对level-0的每一个sstable文件建立一 ...
- 服务器TIME_WAIT和CLOSE_WAIT详解和解决办法
转载的服务器TIME_WAIT和CLOSE_WAIT详解和解决办法
- Spring绑定表单数据
Spring提供了一些jsp页面常用的form标签,很大程度上提高了我们开发的速度,不用再一个个的标签去绑定属性,而且后台接收数据也很简单,可以直接接收object对象作为属性.官方form标签介绍的 ...