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


相关文章
|
6天前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名
【4月更文挑战第22天】Pandas Python库提供数据排序和排名功能。使用`sort_values()`按列进行升序或降序排序,如`df.sort_values(by=&#39;A&#39;, ascending=False)`。`rank()`函数用于计算排名,如`df[&#39;A&#39;].rank(ascending=False)`。多列操作可传入列名列表,如`df.sort_values(by=[&#39;A&#39;, &#39;B&#39;], ascending=[True, False])`和分别对&#39;A&#39;、&#39;B&#39;列排名。
24 2
|
6天前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名?
Pandas在Python中提供数据排序和排名功能。使用`sort_values()`进行排序,如`df.sort_values(by=&#39;A&#39;, ascending=False)`进行降序排序;用`rank()`进行排名,如`df[&#39;A&#39;].rank(ascending=False)`进行降序排名。多列操作可传入列名列表,如`df.sort_values(by=[&#39;A&#39;, &#39;B&#39;], ascending=[True, False])`。
33 6
|
6天前
|
Python
python sort和sorted的区别
在Python中,sort()和sorted()都是用于排序的函数,但它们之间存在一些关键的区别,这些区别主要体现在它们的应用方式、操作对象以及对原始数据的影响上。
|
6天前
|
数据可视化 数据处理 索引
Python如何对数据进行排序和排名操作?
Python如何对数据进行排序和排名操作?
44 0
|
6天前
|
算法 Python
Python中不使用sort对列表排序的技术
Python中不使用sort对列表排序的技术
20 1
|
6天前
|
Python
使用Python pandas的sort_values()方法可按一个或多个列对DataFrame排序
【5月更文挑战第2天】使用Python pandas的sort_values()方法可按一个或多个列对DataFrame排序。示例代码展示了如何按'Name'和'Age'列排序 DataFrame。先按'Name'排序,再按'Age'排序。sort_values()的by参数接受列名列表,ascending参数控制排序顺序(默认升序),inplace参数决定是否直接修改原DataFrame。
27 1
|
6天前
|
存储 索引 Python
python学习5-列表的创建、增删改查、排序
python学习5-列表的创建、增删改查、排序
|
6天前
|
C++ Python
623: 程序设计C 实验五 题目六 排序查找(python)
623: 程序设计C 实验五 题目六 排序查找(python)
|
6天前
|
算法 Python
数据结构与算法 经典排序方法(Python)
数据结构与算法 经典排序方法(Python)
25 0
|
6天前
|
Python
Python系列(22)—— 排序函数
Python系列(22)—— 排序函数