python sorted排序

Python不仅提供了list.sort()方法来实现列表的排序,而且提供了内建sorted()函数来实现对复杂列表的排序以及按照字典的key和value进行排序。

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排序的更多相关文章

  1. python sorted排序用法详解

    sorted排序 python sorted 排序 1. operator函数在介绍sorted函数之前需要了解一下operator函数. operator函数是python的内置函数,提供了一系列常 ...

  2. python 字典排序 关于sort()、reversed()、sorted()

    一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...

  3. <转>python字典排序 关于sort()、reversed()、sorted()

    一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...

  4. Python 列表排序方法reverse、sort、sorted操作方法

    python语言中的列表排序方法有三个:reverse反转/倒序排序.sort正序排序.sorted可以获取排序后的列表.在更高级列表排序中,后两中方法还可以加入条件参数进行排序. reverse() ...

  5. python高阶函数——sorted排序算法

    python 内置的sorted()函数可以对一个list进行排序: >>> sorted([8,3,8,11,-2]) [-2, 3, 8, 8, 11] 既然说是高阶函数,那么它 ...

  6. python之排序(sort/sorted)

    大家都知道,python排序有内置的排序函数 sort() 和 高阶函数sorted() .但是它们有什么区别呢? 让我们先从这个函数的定义说起: sorted():该函数第一个参数iterable为 ...

  7. python的sorted排序具体解释

    排序.在编程中常常遇到的算法.我也在几篇文章中介绍了一些关于排序的算法. 有的高级语言内置了一些排序函数.本文讲述Python在这方面的工作.供使用python的程序猿们參考,也让没有使用python ...

  8. Python中自定义类未定义__lt__方法使用sort/sorted排序会怎么处理?

    在<第8.23节 Python中使用sort/sorted排序与"富比较"方法的关系分析>中介绍了排序方法sort和函数sorted在没有提供key参数的情况下默认调用 ...

  9. python中的sort、sorted排序

    我们通常会遇到对数据库中的数据进行排序的问题,今天学习一下对列表和字典的排序方法. 列表 第一种:内建方法sort sort()对列表排序是永久性的排序. 用法:sort(*, key=None, r ...

随机推荐

  1. 基于Xenomai和工控机的实时测控系统的研究

    http://www.docin.com/p-1006254643-f6.html

  2. Wind7系统下 wifi设置

    netsh wlan set hostednetwork  mode=allow ssid=pass:123456789 key=123456789 netsh wlan set hostednetw ...

  3. SVN使用总结

    ## 常用命令 建立分支 --- svn copy/cp svn cp http://example.com/repos/myproject/trunk http://example.com/repo ...

  4. 数据库.bak文件还原报错的处理办法

    今天从网上下了个Demo,里面有个.bak文件,就试着还原了一下,结果发现报了错.是了两种方式导入,都不行. 最终找到了解决办法: 可以直接用sql语句对.bak文件进行还原. RESTORE DAT ...

  5. RSpec shared examples with template methods

    It’s pretty common to have multiple tests that are nearly the same. In one app, we support bidding o ...

  6. STM32之PWM波形输出配置总结

    一.   TIMER分类: STM32中一共有11个定时器,其中TIM6.TIM7是基本定时器:TIM2.TIM3.TIM4.TIM5是通用定时器:TIM1和TIM8是高级定时器,以及2个看门狗定时器 ...

  7. shell数组操作

    1.数组定义,shell使用一对括号表示数组,数组元素间用"空格"分隔 # 空数组arr1 arr1=() # 数组arr2,成员分别是1, 2, 3, 4, 5, 6 arr2= ...

  8. command not found,系统很多命令都用不了 ,修改环境变量

    bash: ***: command not found,系统很多命令都用不了,均提示没有此命令. 突然之间linux很多命令都用不了,均提示没有此命令. 这应该是系统环境变量出现了问题导致的. 解决 ...

  9. 20151012 C# 第一篇 字符与字符串

    20151012 字符与字符串: Char.String等类来表示 字符类Char 1. 字符类Char 表示一个 Unicode 字符,(Unicode字符是计算机通用的字符编码,对不同语言中的每个 ...

  10. Python和C扩展实现方法

    一.Python和C扩展 cPython是C编写的,python的扩展可以用C来写,也便于移植到C++. 编写的Python扩展,需要编译成一个.so的共享库. Python程序中. 官方文档:htt ...