前言
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-8
a = [-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學習交流群:778463939
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 the
reverse 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學習交流群:778463939
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)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/200489.html
標籤:Python
下一篇:從底層剖析Python深淺拷貝
