1. 程式人生 > >python筆記18-sort和sorted區別

python筆記18-sort和sorted區別

BE 使用 tor nta 筆記 隊列 scrip Coding def

前言

python的排序有兩個方法,一個是list對象的sort方法,另外一個是builtin函數裏面sorted,主要區別:

  • sort僅針對於list對象排序,無返回值, 會改變原來隊列順序
  • sorted是一個單獨函數,可以對可叠代(iteration)對象排序,不局限於list,它不改變原生數據,重新生成一個新的隊列

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

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

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

# coding:utf-8

# 字符串也可以排序

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筆記18-sort和sorted區別