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

 

 

 


本文 由 cococo点点 创作,采用 知识共享 署名-非商业性使用-相同方式共享 3.0 中国大陆 许可协议进行许可。欢迎转载,请注明出处:
转载自:cococo点点 http://www.cnblogs.com/coder2012

时间: 2024-08-03 16:47:17

python sorted排序的相关文章

王亟亟的Python学习之路(九)-sorted()排序以及简单字符串处理

转载请注明出处:王亟亟的大牛之路 这一片就讲2个知识点,1排序,2字符串处理 Python在排序操作的这一部分做了很好的封装,我们不需要写太多代码就可以实现排序的效果,先贴下Java的实现.(这里不是黑Java!!!!) public class 直接插入排序 { public static void main(String[] args) { int[] a={49,38,65,97,76,13,27,49,78,34,12,64,1}; System.out.println("排序之前:&q

python数字排序练习

题目很简单,要求: 2 9 5 7 6 1 4 8 3 5 4 2 求每行的最大值 最近刚好在学习python,感觉py也可以做出来. #!/usr/bin/env python # -*- condig:utf-8 -*- alist = [2,9,5,7] print sorted(alist,reverse=True)[0] blist = [6,1,4,8] print sorted(blist,reverse=True)[0] clist = [3,5,4,2] print sorte

python选择排序算法实例总结

  本文实例总结了python选择排序算法.分享给大家供大家参考.具体如下: 代码1: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def ssort(V): #V is the list to be sorted j = 0 #j is the "current" ordered position, starting with the first one in the list while j != len(V): #this is the replacin

python字典排序实例详解

  本文实例分析了python字典排序的方法.分享给大家供大家参考.具体如下: 1. 准备知识: 在python里,字典dictionary是内置的数据类型,是个无序的存储结构,每一元素是key-value对: 如:dict = {'username':'password','database':'master'},其中'username'和'database'是key,而'password'和'master'是value,可以通过d[key]获得对应值value的引用,但是不能通过value得

python选择排序算法的实现代码_python

1.算法:对于一组关键字{K1,K2,-,Kn}, 首先从K1,K2,-,Kn中选择最小值,假如它是 Kz,则将Kz与 K1对换:然后从K2,K3,- ,Kn中选择最小值 Kz,再将Kz与K2对换.如此进行选择和调换n-2趟,第(n-1)趟,从Kn-1.Kn中选择最小值 Kz将Kz与Kn-1对换,最后剩下的就是该序列中的最大值,一个由小到大的有序序列就这样形成. 2.python 选择排序代码: 复制代码 代码如下: def selection_sort(list2):    for i in

python字符串排序方法_python

本文以实例形式简述了Python实现字符串排序的方法,是Python程序设计中一个非常实用的技巧.分享给大家供大家参考之用.具体方法如下: 一般情况下,python中对一个字符串排序相当麻烦: 一.python中的字符串类型是不允许直接改变元素的.必须先把要排序的字符串放在容器里,如list. 二.python中的list容器的sort()函数没返回值. 所以在python中对字符串排序往往需要好几行代码. 具体实现方法如下: >>> s = "string" >

Python选择排序、冒泡排序、合并排序代码实例_python

前两天刚装了python 3.1.1, 禁不住技痒写点code.1.选择排序 复制代码 代码如下: >>> def SelSort(L):     length=len(L)     for i in range(length-1):         minIdx=i         minVal=L[i]         j=i+1         while j<length:             if minVal>L[j]:                 min

python sorted三个例子

# 例1. 按照元素出现的次数来排序 seq = [2,4,3,1,2,2,3] # 按次数排序 seq2 = sorted(seq, key=lambda x:seq.count(x)) print(seq2) # [4, 1, 3, 3, 2, 2, 2] # 改进:第一优先按次数,第二优先按值 seq3 = sorted(seq, key=lambda x:(seq.count(x), x)) print(seq3) # [1, 4, 3, 3, 2, 2, 2] ''' 原理: 先比较元

python计数排序和基数排序算法实例_python

一.计数排序 计数排序(Counting sort)是一种稳定的排序算法 算法的步骤如下:找出待排序的数组中最大和最小的元素统计数组中每个值为i的元素出现的次数,存入数组C的第i项对所有的计数累加(从C中的第一个元素开始,每一项和前一项相加)反向填充目标数组:将每个元素i放在新数组的第C(i)项,每放一个元素就将C(i)减去1当输入的元素是 n 个 0 到 k 之间的整数时,计数排序的时间复杂度为O(N+K),空间复杂度为O(N+K).当K不是很大时,这是一个很有效的线性排序算法. 以下是测试代