python排序函数sort与sorted的区别及高级用法

一,区别

sort是列表自带函数,其他数据类型不可用,另外它会改变原列表,返回None;sorted的适用范围广泛,不会改变原列表,返回排序后的新列表。

>>> s=(3,2,1)
>>> s.sort()
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    s.sort()
AttributeError: 'tuple' object has no attribute 'sort'
>>> sorted(s)
[1, 2, 3]
>>> s
(3, 2, 1)

二,高级用法

sorted() 函数功能非常强大,它可以方便地针对不同的数据结构进行排序,从而满足不同需求。例子如下:

  • 对字典进行排序
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})     # 根据字典键排序
[1, 2, 3, 4, 5]
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}.values())    # 根据字典值排序
['A', 'B', 'B', 'D', 'E']
  • 对多维列表排序
>>> student_tuples = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10)]
>>> sorted(student_tuples, key = lambda student: student[0]) # 对姓名排序
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(student_tuples, key = lambda student: student[2])  # 年龄排序
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
  • 调用operator模块中的 itemgetter() 可以实现根据多个参数排序
>>> sorted(student_tuples, key = itemgetter(2))  # 根据年龄排序
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(student_tuples, key = itemgetter(1, 2))  # 根据成绩和年龄排序
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
>>> sorted(student_tuples, key = itemgetter(1, 2), reverse=True) # 反转排序结果
[('jane', 'B', 12), ('dave', 'B', 10), ('john', 'A', 15)]
  • 自定义排序规则
import functools
def cmp(a,b):
    if a[0]!=b[0]:
        if a[0]<b[0]:
            return -1
        else:
            return 1
    else:
        if a[1]<b[1]:
            return -1
        elif a[1]==b[1]:
            return 0
        else:
            return 1
s=[[1,3],[1,2],[2,4],[1,4]]
s=sorted(s,key=functools.cmp_to_key(cmp))
print(s)
[[1, 2], [1, 3], [1, 4], [2, 4]]

 

posted @ 2020-10-16 23:51  Marvin-wen  阅读(712)  评论(0编辑  收藏  举报