date: 2021-06-12title: Python之sorted函数及用法 #标题
tags: python #标签
categories: python # 分类

sorted() 作为 Python 内置函数之一,其功能是对可迭代对象(列表、元组、字典、集合、还包括字符串)进行排序。
sorted()函数的基本语法格式如下:

  1. list = sorted(iterable, key=None, reverse=False)
  2. '''
  3. 其中,iterable表示指定的可迭代对象,
  4. key参数可以自定义排序规则,
  5. reverse参数指定以升序还是降序排列,默认升序,
  6. sorted()函数会返回一个排好序的列表。
  7. '''

注意:key参数和reverse参数是可选参数,可以指定,也可以为空

sorted使用示例

  1. # 对列表进行排序
  2. a = [5, 3, 4, 2, 1]
  3. print(sorted(a))
  4. # 对元组进行排序
  5. a = (5, 4, 3, 2, 1)
  6. print(sorted(a))
  7. # 字典默认按照key进行排序
  8. a = {4: 1, \
  9. 5: 2, \
  10. 3: 3, \
  11. 2: 6, \
  12. 1: 8}
  13. print(sorted(a.items()))
  14. # 对集合进行排序
  15. a = {1, 5, 3, 2, 4}
  16. print(sorted(a))
  17. # 对字符串进行排序
  18. a = 'fedacb'
  19. print(sorted(a))
  20. '''
  21. 打印结果如下:
  22. [1, 2, 3, 4, 5]
  23. [1, 2, 3, 4, 5]
  24. [(1, 8), (2, 6), (3, 3), (4, 1), (5, 2)]
  25. [1, 2, 3, 4, 5]
  26. ['a', 'b', 'c', 'd', 'e', 'f']
  27. '''

使用sorted()函数对可迭代对象进行排序,并不会修改原对象,而是生成一个新排好序的列表。

sorted()函数默认对序列中元素进行升序排序,通过手动将其 reverse 参数值改为 True,可实现降序排序。例如:

  1. #对列表进行排序
  2. a = [5,3,4,2,1]
  3. print(sorted(a,reverse=True))
  4. # 返回结果如下:
  5. [5, 4, 3, 2, 1]

sorted结合key使用

在调用 sorted() 函数时,还可传入一个 key 参数,它可以接受一个函数,该函数的功能是指定 sorted() 函数按照什么标准进行排序。例如:

  1. chars = ['http://c.biancheng.net', \
  2. 'http://c.biancheng.net/python/', \
  3. 'http://c.biancheng.net/shell/', \
  4. 'http://c.biancheng.net/java/', \
  5. 'http://c.biancheng.net/golang/']
  6. # 默认排序
  7. print(sorted(chars))
  8. # 自定义按照字符串长度排序
  9. print(sorted(chars, key=lambda x: len(x)))
  10. # 返回结果如下:
  11. ['http://c.biancheng.net', 'http://c.biancheng.net/golang/', 'http://c.biancheng.net/java/', 'http://c.biancheng.net/python/', 'http://c.biancheng.net/shell/']
  12. ['http://c.biancheng.net', 'http://c.biancheng.net/java/', 'http://c.biancheng.net/shell/', 'http://c.biancheng.net/python/', 'http://c.biancheng.net/golang/']

sorted实战案例

l1 = [
    {'seles_volume': 123},
    {'seles_volume': 125},
    {'seles_volume': 122},
    {'seles_volume': 225},
    {'seles_volume': 876},
]

print(sorted(l1, key=lambda x: x.get('seles_volume'), reverse=True))