date: 2021-06-12title: Python之sorted函数及用法 #标题
tags: python #标签
categories: python # 分类
sorted() 作为 Python 内置函数之一,其功能是对可迭代对象(列表、元组、字典、集合、还包括字符串)进行排序。
sorted()函数的基本语法格式如下:
list = sorted(iterable, key=None, reverse=False)
'''
其中,iterable表示指定的可迭代对象,
key参数可以自定义排序规则,
reverse参数指定以升序还是降序排列,默认升序,
sorted()函数会返回一个排好序的列表。
'''
注意:key参数和reverse参数是可选参数,可以指定,也可以为空
sorted使用示例
# 对列表进行排序
a = [5, 3, 4, 2, 1]
print(sorted(a))
# 对元组进行排序
a = (5, 4, 3, 2, 1)
print(sorted(a))
# 字典默认按照key进行排序
a = {4: 1, \
5: 2, \
3: 3, \
2: 6, \
1: 8}
print(sorted(a.items()))
# 对集合进行排序
a = {1, 5, 3, 2, 4}
print(sorted(a))
# 对字符串进行排序
a = 'fedacb'
print(sorted(a))
'''
打印结果如下:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[(1, 8), (2, 6), (3, 3), (4, 1), (5, 2)]
[1, 2, 3, 4, 5]
['a', 'b', 'c', 'd', 'e', 'f']
'''
使用sorted()函数对可迭代对象进行排序,并不会修改原对象,而是生成一个新排好序的列表。
sorted()函数默认对序列中元素进行升序排序,通过手动将其 reverse 参数值改为 True,可实现降序排序。例如:
#对列表进行排序
a = [5,3,4,2,1]
print(sorted(a,reverse=True))
# 返回结果如下:
[5, 4, 3, 2, 1]
sorted结合key使用
在调用 sorted() 函数时,还可传入一个 key 参数,它可以接受一个函数,该函数的功能是指定 sorted() 函数按照什么标准进行排序。例如:
chars = ['http://c.biancheng.net', \
'http://c.biancheng.net/python/', \
'http://c.biancheng.net/shell/', \
'http://c.biancheng.net/java/', \
'http://c.biancheng.net/golang/']
# 默认排序
print(sorted(chars))
# 自定义按照字符串长度排序
print(sorted(chars, key=lambda x: len(x)))
# 返回结果如下:
['http://c.biancheng.net', 'http://c.biancheng.net/golang/', 'http://c.biancheng.net/java/', 'http://c.biancheng.net/python/', 'http://c.biancheng.net/shell/']
['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))