sorted常见的参数:key表示以哪个维度作比较, reverse表示是否倒序,默认是False
1.对list排序
a = [3, 1, 7, 8]
sorted(a)
# [1, 3, 7, 8]
- 按照指定的某一个元素排序
a = [('a',0.1),('b',0.01),('c',0.2)]
sorted(search_ret,key=lambdax:x[1],reverse=False)
# [('b', 0.01), ('a', 0.1), ('c', 0.2)]
- 按照指定的某几个元素分优先级排序
from operator import itemgetter
a = [(4, 0.1), (6, 0.05), (5, 0.1), (1, 0.2)]
sorted(a, key=itemgetter(1, 0), reverse=False)
# [(6, 0.05), (4, 0.1), (5, 0.1), (1, 0.2)]
- 按照value对字典排序(其实就是第2种情况)
d = {'a':2, 'f':4,'s':1}
sorted(d.items(), key=lambda x: x[1])
# [('s', 1), ('a', 2), ('f', 4)]