python sorted排序

來源:互聯網
上載者:User

標籤:

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排序

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.