python排序的两个方法
生活随笔
收集整理的這篇文章主要介紹了
python排序的两个方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
python的排序有兩個方法,一個是list對象的sort方法,另外一個是builtin函數里面sorted,主要區別:
- sort僅針對于list對象排序,無返回值, 會改變原來隊列順序
- sorted是一個單獨函數,可以對可迭代(iteration)對象排序,不局限于list,它不改變原生數據,重新生成一個新的隊列
本篇是基于python3.6講解的,python2會多一個cmp參數,cmp函數在python3上已經丟棄了
cmp(x,y)函數用于比較2個對象,如果 x < y返回 -1, 如果x == y返回 0, 如果 x > y 返回 1。
sort方法
1.sort是list對象的方法,通過.sort()來調用
>>> help(list.sort) Help on method_descriptor:sort(...)L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*>>>2.參數說明:
- key 用列表元素的某個屬性或函數進行作為關鍵字(此函數只能有一個參數)
- reverse 排序規則. reverse = True 降序 或者 reverse = False 升序,默認升序
- return 無返回值
3.使用方法介紹
# coding:utf-8a = [-9, 2, 3, -4, 5, 6, 6, 1]# 按從小到大排序 a.sort() print(a) # 結果:[-9, -4, 1, 2, 3, 5, 6, 6]# 按從大到小排序 a.sort(reverse=True) print(a) # 結果:[6, 6, 5, 3, 2, 1, -4, -9]4.key參數接受的是函數對象,并且函數只能有一個參數,可以自己定義一個函數,也可以寫個匿名函數(lambda)
# coding:utf-8 # 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 # 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! a = [-9, 2, 3, -4, 5, 6, 6, 1] # 按絕對值排序 def f(x):return abs(x) a.sort(key=f) print(a) # 結果:[1, 2, 3, -4, 5, 6, 6, -9]# 1、list對象是字符串 b = ["hello", "helloworld", "he", "hao", "good"] # 按list里面單詞長度倒敘 b.sort(key=lambda x: len(x), reverse=True) print(b) # 結果:['helloworld', 'hello', 'good', 'hao', 'he']# 2、.list對象是元組 c = [("a", 9), ("b", 2), ("d", 5)]# 按元組里面第二個數排序 c.sort(key=lambda x: x[1]) print(c) # 結果:[('b', 2), ('d', 5), ('a', 9)]# 3、list對象是字典 d = [{"a": 9}, {"b": 2}, {"d":5}]d.sort(key=lambda x: list(x.values())[0]) print(d) # 結果:[{'b': 2}, {'d': 5}, {'a': 9}]sorted函數
1.sorted是python里面的一個內建函數,直接調用就行了
>>> help(sorted) 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 thereverse flag can be set to request the result in descending order.>>>2.參數說明
- iterable 可迭代對象,如:str、list、tuple、dict都是可迭代對象(這里就不局限于list了)
- key 用列表元素的某個屬性或函數進行作為關鍵字(此函數只能有一個參數)
- reverse 排序規則. reverse = True 降序或者 reverse = False 升序,默認升序
- return 有返回值值,返回新的隊列
3.使用方法介紹
# coding:utf-8 # 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 # 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! a = [-9, 2, 3, -4, 5, 6, 6, 1]# 按從小到大排序 b = sorted(a) print(a) # a不會變 print(b) # b是新的隊列 [-9, -4, 1, 2, 3, 5, 6, 6]# 按從大到小排序 c = sorted(a, reverse=True) print(c) # 結果:[6, 6, 5, 3, 2, 1, -4, -9]4.可迭代對象iterable都可以排序,返回結果會重新生成一個list
# 字符串也可以排序s = "hello world!" d = sorted(s) print(d) # 結果:[' ', '!', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']# 元組也可以排序 t = (-9, 2, 7, 3, 5) n = sorted(t) print(n) # 結果:[-9, 2, 3, 5, 7]# dict按value排序 f = {"a": 9, "b": 2, "d": 5} g = sorted(f.items(), key=lambda x: x[1]) print(g) # 結果:[('b', 2), ('d', 5), ('a', 9)]總結
以上是生活随笔為你收集整理的python排序的两个方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python列表元素操作相关的2个函数和
- 下一篇: Python教程:对 a = [lamb