(轉)Python中sort和sorted的區別和使用方法


原文地址:"https://www.cnblogs.com/whaben/p/6495702.html"

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

key=lambda 元素: 元素[字段索引] 
例如:想對元素第二個字段排序,則key=lambda y: y[1],相對元素第一個字段排序,則key=lambda y: y[0]
備注:這里y可以是任意字母,等同key=lambda x: x[1]或者key=lambda x: x[0]

>>>list = [('a', 4), ('b', 2), ('c', 5), ('d', 3), ('e', 1)]
>>>print(sorted(list, key=lambda x: x[0])) #對第一個元素排序
>>>print(sorted(list, key=lambda y: y[1])) #對第二個元素排序
[('a', 4), ('b', 2), ('c', 5), ('d', 3), ('e', 1)]
[('e', 1), ('b', 2), ('d', 3), ('a', 4), ('c', 5)]

同樣的技術對擁有命名屬性的復雜對象也適用,例如:

>>> 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模塊有itemgetter,attrgetter,從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)]

methodcaller的作用與 attrgetter 和 itemgetter 類似,它會自行創建函數,該函數會在對象上調用參數指定的方法:

>>> from operator import methodcaller 
>>> s = 'The time has come' 
>>> upcase = methodcaller('upper') 
>>> upcase(s)
'THE TIME HAS COME' 
>>> hiphenate = methodcaller('replace', ' ', '-') 
>>> hiphenate(s) 
'The-time-has-come'

如果把多個參數傳給 itemgetter 或者 attrgetter,它構建的函數會返回提取的值構成的元組:

>>> metro_data = [('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889))]
>>> cc_name = itemgetter(1, 0) 
>>> for city in metro_data:
>>>     print(cc_name(city))
('JP', 'Tokyo') ('IN', 'Delhi NCR') 

如果參數名中包含 .(點號),attrgetter 會深入嵌套對象,獲取指定的屬性:

>>> from collections import namedtuple 
>>> LatLong = namedtuple('LatLong', 'lat long')  #
>>> Metropolis = namedtuple('Metropolis', 'name cc pop coord')  #
>>> metro_areas = [Metropolis(name, cc, pop, LatLong(lat, long))  #
>>>     for name, cc, pop, (lat, long) in metro_data] 
>>> metro_areas[0] 
Metropolis(name='Tokyo', cc='JP', pop=36.933, coord=LatLong(lat=35.689722, long=139.691667)) 
>>> metro_areas[0].coord.lat  #
35.689722 
>>> from operator import attrgetter 
>>> name_lat = attrgetter('name', 'coord.lat')  #
>>> for city in sorted(metro_areas, key=attrgetter('coord.lat')):  #
>>>     print(name_lat(city))  #
('Sao Paulo', -23.547778)
('Mexico City', 19.433333) 
('Delhi NCR', 28.613889)
('Tokyo', 35.689722) 
('New York-Newark', 40.808611)

❶ 使用 namedtuple 定義 LatLong。

❷ 再定義 Metropolis。

❸ 使用 Metropolis 實例構建 metro_areas 列表;注意,我們使用嵌套的元組拆包提取 (lat, long),然后使用它們構建 LatLong,作為 Metropolis 的 coord 屬性。

❹ 深入 metro_areas[0],獲取它的緯度。

❺ 定義一個 attrgetter,獲取 name 屬性和嵌套的 coord.lat 屬性。

❻ 再次使用 attrgetter,按照緯度排序城市列表。

❼ 使用標號❺中定義的 attrgetter,只顯示城市名和緯度。

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)最老土的排序方法-DSU

我們稱其為DSU(Decorate-Sort-Undecorate),原因為排序的過程需要下列三步:
第一:對原始的list進行裝飾,使得新list的值可以用來控制排序;
第二:對裝飾后的list排序;
第三:將裝飾刪除,將排序后的裝飾list重新構建為原來類型的list;
 

例如,使用DSU方法來對student數據根據grade排序:
>>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)]
>>> decorated.sort()
>>> [student for grade, i, student in decorated]               # undecorate
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
上面的比較能夠工作,原因是tuples是可以用來比較,tuples間的比較首先比較tuples的第一個元素,如果第一個相同再比較第二個元素,以此類推。
 

並不是所有的情況下都需要在以上的tuples中包含索引,但是包含索引可以有以下好處:
第一:排序是穩定的,如果兩個元素有相同的key,則他們的原始先后順序保持不變;
第二:原始的元素不必用來做比較,因為tuples的第一和第二元素用來比較已經是足夠了。
 

此方法被RandalL.在perl中廣泛推廣后,他的另一個名字為也被稱為Schwartzian transform。

對大的list或list的元素計算起來太過復雜的情況下,在python2.4前,DSU很可能是最快的排序方法。但是在2.4之后,上面解釋的key函數提供了類似的功能。

7)其他語言普遍使用的排序方法-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.7,cmp_to_key()函數被增加到了functools模塊中。

8)其他注意事項

* 對需要進行區域相關的排序時,可以使用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()不是最好的方法。在這種情況下,可以使用heap,red-black tree或treap。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM