python - how to sort

來源:互聯網
上載者:User

標籤:ack   lam   iterable   repr   lex   ges   效率   init   cti   

python - how to sort

 

  1.  overview
  2. Key function (★★★★★)
  3.  OPerator module functions
  4. asc and desc 升序和降序

 

Overview

對於python 列表,有一個方法 list.sort()  ,另外還有一個內建函數sorted()

list.sort() 是對本身排序,不會產生新的對象。而sorted 接收一個可迭代對象,返回一個新的排好序的list

 

Help on built-in function sorted in module builtins:sorted(iterable, /, *, key=None, reverse=False)    Return a new list containing all items from the iterable in ascending order.        A custom key function can be supplied to customize the sort order, and the    reverse flag can be set to request the result in descending order

 

>>> help(list.sort)Help on method_descriptor:sort(...)    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

 

 list.sort() 會把原始列表修改,return None ,當你不需要原始列表的時候,這個方法會更有效率。

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

 


sorted()  這個方法用起來比較方便

 >>> sorted([6,3,8,12,4])[3, 4, 6, 8, 12]>>> 

 

 sorted() 接收可迭代對象

eg.

 

比如

>>> dic={4:‘a‘,2:‘b‘,3:‘A‘,1:‘h‘}>>> sorted(dic)[1, 2, 3, 4]

 

 

Key function

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element
prior to making comparisons

list.sort()和sorted()都有一個關鍵參數來指定在每個列表元素上被調用的函數在進行比較之前。

for example:

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

 

The value of the key parameter should be a function that takes a single argument and returns a key to use
for sorting purposes. This technique is fast because the key function is called exactly once for each input
record

key 參數的值應該是一個函數對象,這個函數對象帶一個參數,返回一個key,這個key 就是排序的標準,

 
class Student(object):    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))ls_grade = sorted([    Student(‘join‘,90,15),    Student(‘alex‘,87,13),    Student(‘eleven‘,100,17)    ],key=lambda stu:stu.grade)ls_age = sorted([    Student(‘join‘,90,15),    Student(‘alex‘,87,17),    Student(‘eleven‘,100,14)    ],key=lambda stu:stu.age)print(ls_grade)print(ls_age)

 

  OPerator module functions

 

  asc and desc 升序和降序

預設是升序排序

reverse 預設是false ,如果是true ,那就是降序排列

sorted 和list.sort() 的排序是穩定排序

 

于洋 回到頂部

python - how to sort

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.