【轉載】 python sort、sorted進階排序技巧

來源:互聯網
上載者:User

標籤:ram   外部   python2.x   gpo   desc   and   表示   func   ted   

這篇文章主要介紹了python sort、sorted進階排序技巧,本文講解了基礎排序、升序和降序、排序的穩定性和複雜排序、cmp函數排序法等內容,需要的朋友可以參考下

Python list內建sort()方法用來排序,也可以用python內建的全域sorted()方法來對可迭代的序列排序產生新的序列。

1. 排序基礎

簡單的升序排序是非常容易的。只需要調用sorted()方法。它返回一個新的list,新的list的元素基於小於運算子(lt)來排序。

>>> sorted([5, 2, 3, 1, 4])[1, 2, 3, 4, 5]

你也可以使用list.sort()方法來排序,此時list本身將被修改。通常此方法不如sorted()方便,但是如果你不需要保留原來的list,此方法將更有效。

>>> a = [5, 2, 3, 1, 4]>>> a.sort()>>> a[1, 2, 3, 4, 5]

另一個不同就是list.sort()方法僅被定義在list中,相反地sorted()方法對所有的可迭代序列都有效。

>>>sorted({1: ‘D‘, 2: ‘B‘, 3: ‘B‘, 4: ‘E‘, 5: ‘A‘})[1, 2, 3, 4, 5]
2. key參數/函數

python2.4開始,list.sort()sorted()函數增加了key參數來指定一個函數,此函數將在每個元素比較前被調用。 例如通過key指定的函數來忽略字串的大小寫:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)[‘a‘, ‘Andrew‘, ‘from‘, ‘is‘, ‘string‘, ‘test‘, ‘This‘]

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)]
3. Operator 模組函數

上面的key參數的使用非常廣泛,因此python提供了一些方便的函數來使得存取方法更加容易和快速。operator模組有itemgetterattrgetter,從2.6開始還增加了methodcaller方法。使用這些方法,上面的操作將變得更加簡潔和快速:

>>> from operator import itemgetter, attrgetter>>> sorted(student_tuples, key=itemgetter(2))[(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]>>> sorted(student_objects, key=attrgetter(‘age‘))[(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]

operator模組還允許多級的排序,例如,先以grade,然後再以age來排序

>>> sorted(student_tuples, key=itemgetter(1,2))[(‘john‘, ‘A‘, 15), (‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12)]>>> sorted(student_objects, key=attrgetter(‘grade‘, ‘age‘))[(‘john‘, ‘A‘, 15), (‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12)]
4. 升序和降序

list.sort()sorted()都接受一個參數reverse(True or False)來表示升序或降序排序。例如對上面的student降序排序如下:

>>> sorted(student_tuples, key=itemgetter(2), reverse=True)[(‘john‘, ‘A‘, 15), (‘jane‘, ‘B‘, 12), (‘dave‘, ‘B‘, 10)]>>> sorted(student_objects, key=attrgetter(‘age‘), reverse=True)[(‘john‘, ‘A‘, 15), (‘jane‘, ‘B‘, 12), (‘dave‘, ‘B‘, 10)]
5. 排序的穩定性和複雜排序

python2.2開始,排序被保證為穩定的。意思是說多個元素如果有相同的key,則排序前後他們的先後順序不變。

>>> data = [(‘red‘, 1), (‘blue‘, 1), (‘red‘, 2), (‘blue‘, 2)]>>> sorted(data, key=itemgetter(0))[(‘blue‘, 1), (‘blue‘, 2), (‘red‘, 1), (‘red‘, 2)]

注意在排序後‘blue‘的順序被保持了,即‘blue‘, 1在‘blue‘, 2的前面。

更複雜地你可以構建多個步驟來進行更複雜的排序,例如對student資料先以grade降序排列,然後再以age升序排列。

>>> s = sorted(student_objects, key=attrgetter(‘age‘))     # sort on secondary key>>> sorted(s, key=attrgetter(‘grade‘), reverse=True)       # now sort on primary key, descending[(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]
6. 其他語言普遍使用的排序方法-cmp函數

python2.4前,sorted()list.sort()函數沒有提供key參數,但是提供了cmp參數來讓使用者指定比較函數。此方法在其他語言中也普遍存在。

python3.0中,cmp參數被徹底的移除了,從而簡化和統一語言,減少了進階比較和__cmp__方法的衝突。

在python2.x中cmp參數指定的函數用來進行元素間的比較。此函數需要2個參數,然後返回負數表示小於,0表示等於,正數表示大於。例如:

>>> 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]

當我們將現有的2.x的代碼移植到3.x時,需要將cmp函數轉化為key函數,以下的wrapper很有協助:

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

當需要將cmp轉化為key時,只需要:

>>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))[5, 4, 3, 2, 1]

python2.7cmp_to_key()函數被增加到了functools模組中。

7. 其他注意事項
  • 對需要進列區域相關的排序時,可以使用locale.strxfrm()作為key函數,或者使用local.strcoll()作為cmp函數。

  • reverse參數任然保持了排序的穩定性,有趣的時,同樣的效果可以使用reversed()函數兩次來實現:

    >>> data = [(‘red‘, 1), (‘blue‘, 1), (‘red‘, 2), (‘blue‘, 2)]>>> assert sorted(data, reverse=True) == list(reversed(sorted(reversed(data))))
  • 其實排序在內部是調用元素的__cmp__來進行的,所以我們可以為元素類型增加__cmp__方法使得元素可比較,例如:

    >>> Student.__lt__ = lambda self, other: self.age < other.age>>> sorted(student_objects)[(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]
  • key函數不僅可以訪問需要排序元素的內部資料,還可以訪問外部的資源,例如,如果學生的成績是儲存在dictionary中的,則可以使用此dictionary來對學生名字的list排序,如下:

    >>> students = [‘dave‘, ‘john‘, ‘jane‘]>>> newgrades = {‘john‘: ‘F‘, ‘jane‘:‘A‘, ‘dave‘: ‘C‘}>>> sorted(students, key=newgrades.__getitem__)[‘jane‘, ‘dave‘, ‘john‘]

*當你需要在處理資料的同時進行排序的話,sort(), sorted()bisect.insort()不是最好的方法。在這種情況下,可以使用heapred-black treetreap

【轉載】 python sort、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.