Python sort和sorted


Python中用來排序的方法sort、sorted

sort 與 sorted 區別:

  • 1.sort 是應用在 list 上的方法,而sorted 可以對所有可迭代的對象(他們可以是list、dict、set、甚至是字符串)進行排序操作。
  • 2.list 的 sort 方法返回的是對已經存在的列表進行操作,無返回值,而內建函數 sorted 方法返回的是一個新的 list,而不是在原來的基礎上進行的操作。
  • 3.sorted方法為內置方法,sort方法為屬性方法。
  • 4.sort是在原位重新排列列表,而sorted()是產生一個新的列表。
  • 5.推薦使用內置方法,效率更高,所以使用sorted更好。

sort方法原型:
>>> help(list.sort)
L.sort(cmp=None, key=None, reverse=False)

sorted方法原型:
>>> help(sorted)
sorted(iterable,key=None, reverse=False)
參數說明:

  • iterable -- 可迭代對象。
  • cmp -- 比較的函數,這個具有兩個參數,參數的值都是從可迭代對象中取出,此函數必須遵守的規則為,大於則返回1,小於則返回-1,等於則返回0。
  • key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自於可迭代對象中,指定可迭代對象中的一個元素來進行排序。
  • reverse -- 排序規則,reverse = True 降序 , reverse = False 升序(默認)。

 

sorted使用方法

1、對列表排序,返回的對象不會改變原列表,返回新列表

list = [1,5,7,2,4]
sorted(list)
Out[87]: [1, 2, 4, 5, 7]
#可以設定時候排序方式,默認從小到大,設定reverse = False 可以從大到小
sorted(list,reverse=False)
Out[88]: [1, 2, 4, 5, 7]
sorted(list,reverse=True)
Out[89]: [7, 5, 4, 2, 1]

2、根據自定義規則來排序,使用參數:key

# 使用key,默認搭配lambda函數使用
sorted(chars,key=lambda x:len(x))
Out[92]: ['a', 'is', 'boy', 'bruce', 'handsome']

sorted(chars,key=lambda x:len(x),reverse= True)
Out[93]: ['handsome', 'bruce', 'boy', 'is', 'a']

 

3、根據自定義規則來排序,對元組構成的列表進行排序

tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]
#key=lambda x: x[1]中可以任意選定x中可選的位置進行排序
sorted(tuple_list, key=lambda x: x[1]) 

Out[94]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]

sorted(tuple_list, key=lambda x: x[0])
Out[95]: [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)]

sorted(tuple_list, key=lambda x: x[2])
Out[96]: [('B', 3, 2), ('A', 1, 5), ('C', 2, 6)]

4、排序的元素是自定義類

class tuple_list:
    def __init__(self, one, two, three):
        self.one = one
        self.two = two
        self.three = three
    def __repr__(self):
        return repr((self.one, self.two, self.three))

tuple_list_ = [tuple_list('A', 1,5), tuple_list('B', 3,2), tuple_list('C', 2,6)]
sorted(tuple_list_, key=lambda x: x.one)
Out[104]: [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)]
sorted(tuple_list_, key=lambda x: x.two)
Out[105]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]
sorted(tuple_list_, key=lambda x: x.three)
Out[106]: [('B', 3, 2), ('A', 1, 5), ('C', 2, 6)]

5、sorted 也可以根據多個字段來排序

class tuple_list:
    def __init__(self, one, two, three):
        self.one = one
        self.two = two
        self.three = three
    def __repr__(self):
        return repr((self.one, self.two, self.three))

tuple_list_ = [tuple_list('C', 1,5), tuple_list('A', 3,2), tuple_list('C', 2,6)]
# 首先根據one的位置來排序,然后根據two的位置來排序
sorted(tuple_list_, key=lambda x:(x.one, x.two))
Out[112]: [('A', 3, 2), ('C', 1, 5), ('C', 2, 6)]                

6、使用operator 中的itemgetter方法和attrgetter方法

tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]
class tuple_list_class:
    def __init__(self, one, two, three):
        self.one = one
        self.two = two
        self.three = three
    def __repr__(self):
        return repr((self.one, self.two, self.three))
tuple_list_ = [tuple_list_class('C', 1,5), tuple_list_class('A', 3,2), tuple_list_class('C', 2,6)]
from operator import itemgetter
sorted(tuple_list, key=itemgetter(1))
Out[119]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]
from operator import attrgetter
sorted(tuple_list_, key=attrgetter('one')) # attrgetter 傳入的參數必須是str
Out[120]: [('A', 3, 2), ('C', 1, 5), ('C', 2, 6)] 
# 如果是根據多個類的參數排序,按照參數定義順序
from operator import attrgetter
sorted(tuple_list_, key=attrgetter('two','one'))
Out[121]: [('C', 1, 5), ('C', 2, 6), ('A', 3, 2)]

高級用法

有時候,我們要處理的數據內的元素不是一維的,而是二維的甚至是多維的,那要怎么進行排序呢?這時候,sorted()函數內的key參數就派上用場了!從幫助信息上可以了解到,key參數可傳入一個自定義函數。那么,該如何使用呢?讓我們看看如下代碼:

>>>l=[('a', 1), ('b', 2), ('c', 6), ('d', 4), ('e', 3)]
>>>sorted(l, key=lambda x:x[0])
Out[39]: [('a', 1), ('b', 2), ('c', 6), ('d', 4), ('e', 3)]
>>>sorted(l, key=lambda x:x[0], reverse=True)
Out[40]: [('e', 3), ('d', 4), ('c', 6), ('b', 2), ('a', 1)]
>>>sorted(l, key=lambda x:x[1])
Out[41]: [('a', 1), ('b', 2), ('e', 3), ('d', 4), ('c', 6)]
>>>sorted(l, key=lambda x:x[1], reverse=True)
Out[42]: [('c', 6), ('d', 4), ('e', 3), ('b', 2), ('a', 1)]

這里,列表里面的每一個元素都為二維元組,key參數傳入了一個lambda函數表達式,其x就代表列表里的每一個元素,然后分別利用索引返回元素內的第一個和第二個元素,這就代表了sorted()函數利用哪一個元素進行排列。而reverse參數就如同上面講的一樣,起到逆排的作用。默認情況下,reverse參數為False。
當然,正如一開始講到的那樣,如果想要對列表直接進行排序操作,可以用成員方法sort()來做:

>>>l.sort(key=lambda x : x[1])
>>>l
Out[45]: [('a', 1), ('b', 2), ('e', 3), ('d', 4), ('c', 6)]
>>>l.sort(key=lambda x : x[1], reverse=True)
>>>l
Out[47]: [('c', 6), ('d', 4), ('e', 3), ('b', 2), ('a', 1)]

對於三維及以上的數據排排序,上述方法同樣適用。

refer:https://www.jb51.net/article/147635.htm

 


免責聲明!

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



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