sorted语法
sorted(iterable, key=None, reverse=False)
参数说明:
- iterable -- 可迭代对象。
- key --主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
- reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
返回:
- 一个新list对象
①按键key排序
from operator import itemgetter
dict = {3: 'B', 1: 'A', 2: 'C'}
# 按key升序
# 1. dict.items()取得3个(key,value)
# 2. lambda x: x[0]取(key,value)的key 即(3,1,2)
d1 = sorted(dict.items(), key=lambda x: x[0], reverse=False) # <class 'list'>
# 按key降序 itemgetter类似lambda
d2 = sorted(dict.items(), key=itemgetter(0), reverse=True) # <class 'list'>
# 输出
print(d1, type(d1)) # [(1, 'A'), (2, 'C'), (3, 'B')] <class 'list'>
print(d2, type(d2)) # [(3, 'B'), (2, 'C'), (1, 'A')] <class 'list'>
[(1, ‘A’), (2, ‘C’), (3, ‘B’)] <class ‘list’>
[(3, ‘B’), (2, ‘C’), (1, ‘A’)] <class ‘list’>
②按值value排序
from operator import itemgetter
dict = {3: 'B', 1: 'A', 2: 'C'}
# 按value升序
# 1. dict.items()取得3个(key,value)
# 2. lambda x: x[1]取(key,value)的value 即('B','A','C')
d3 = sorted(dict.items(), key=lambda x: x[1], reverse=False) # <class 'list'>
# 按value降序 itemgetter类似lambda
d4 = sorted(dict.items(), key=itemgetter(1), reverse=True) # <class 'list'>
print(d3, type(d3)) # [(1, 'A'), (3, 'B'), (2, 'C')] <class 'list'>
print(d4, type(d4)) # [(2, 'C'), (3, 'B'), (1, 'A')] <class 'list'>
[(1, ‘A’), (3, ‘B’), (2, ‘C’)] <class ‘list’>
[(2, ‘C’), (3, ‘B’), (1, ‘A’)] <class ‘list’>
③按value和key排序
dict = {4:'B', 3: 'B', 1: 'A', 2: 'C', 5: 'A'}
# 按value进行升序,value相同再按key进行降序
d3 = sorted(dict.items(), key=lambda x: (x[1] , -x[0]), reverse=False)
print(d3, type(d3)) # [(5, 'A'), (1, 'A'), (4, 'B'), (3, 'B'), (2, 'C')] <class 'list'>
# 按value进行降序,value相同再按key进行升序
d3 = sorted(dict.items(), key=lambda x: (-ord(x[1]) , x[0]), reverse=False) # 对字符降序比较可以先转ord。如果是'123'字符串数字可以使用int,其他规则请自行延伸。
print(d3, type(d3)) # [(2, 'C'), (3, 'B'), (4, 'B'), (1, 'A'), (5, 'A')] <class 'list'>
[(5, ‘A’), (1, ‘A’), (4, ‘B’), (3, ‘B’), (2, ‘C’)] <class ‘list’>
[(2, ‘C’), (3, ‘B’), (4, ‘B’), (1, ‘A’), (5, ‘A’)] <class ‘list’>
简单总结:排序value和key的区别
dict = {3: 'B', 1: 'A', 2: 'C'}
# dict.items()取得所有的(key,value)键值对,n个键值对视为n个待排的元组
#### 按key排序
# lambda x: x[0] : 取(key,value)的key 即(3,1,2)
# 表示将n个待排的元组(键值对),按(key,value)的key进行排序
#### 按value排序
# lambda x: x[1] : 取(key,value)的value 即('B','A','C')
# 表示将n个待排的元组(键值对),按(key,value)的value进行排序
#### 按value和key排序
# lambda x: (x[1] , -x[0])
# 按value进行升序,value相同再按key进行降序
如果dict里有复杂的数据结构或者可变的数据类型,比如二维数组怎么办呢?请看sorted排序list和dict的混合