Python排序介紹,python排序

來源:互聯網
上載者:User

Python排序介紹,python排序
Python排序介紹

本文簡單記錄了Python中的內建函數 sort() 和 sorted() 的使用方法,以及它們在 Python2 和 Python3 中的區別。

概述

內建函數 sort() 和 sorted() 都可以對一個List進行排序,它們的區別是,sort 對 List 本身進行排序(sorts the list in place),沒有返回,而 sorted 會返回經過排序後的 list。兩者的參數一樣,所進行的排序都是穩定的。

>>> l = [2, 4, 6, 1, 3]>>> l.sort()>>> l[1, 2, 3, 4, 6]>>> l = [2, 4, 6, 1, 3]>>> sorted(l)[1, 2, 3, 4, 6]>>> l[2, 4, 6, 1, 3]
Python3 中的 sorted

Python3 中,內建方法 sorted 定義是:

sorted(iterable[, key][, reverse])

其中

  • iterable 代表待排序資料
  • key 是一個函數,該函數接收一個參數,即iterable 中的每一項,返回需要進行比較的值。預設為None,即比較 item 本身。
  • reverse 是布爾類型,reverse 為 True 時反向排序。預設為 False 。

樣本:

>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]>>> sorted(students, key=lambda x : x[0])[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]>>> sorted(students, key=lambda x : x[2])[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]>>> sorted(students, key=lambda x : x[2], reverse=True)[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]>>>>>> d = {'data1':3, 'data2':1, 'data3':2, 'data4':4}>>> sorted(d.items(), key=lambda x : x[1])[('data2', 1), ('data3', 2), ('data1', 3), ('data4', 4)]
Python2 中的 sorted

Python2 中,內建方法 sorted 定義是:

sorted(iterable[, cmp[, key[, reverse]]])

其中

  • iterable 代表待排序資料
  • cmp 是一個函數,它接收兩個參數,如 cmp(a, b) ,返回負值、0 或者正值,分別代表 a 小於、等於、大於 b
  • key 是一個函數,該函數接收一個參數,即iterable 中的每一項,返回需要進行比較的值。預設為None,即比較 item 本身
  • reverse 是布爾類型,reverse 為 True 時反向排序。預設為 False

樣本:

>>> sorted(students, cmp=lambda x,y : cmp(x[2], y[2]))[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
總結

Python3 相對於 Python2,去掉了 cmp 參數,簡化了函數的使用。對於待比較的兩個值如 a 和 b ,只使用 < 符號的比較結果。

聯繫我們

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