美文网首页
python sorted多列排序

python sorted多列排序

作者: 戚子宇 | 来源:发表于2019-06-26 20:36 被阅读0次

sorted

可以对所有可迭代的对象进行排序操作
也就是说,任意元组、列表、字典互相嵌套的结构都可以用sorted进行排序

sorted 语法

sorted(iterable[, cmp[, key[, reverse]]])

参数 说明
iterable 可迭代对象, 任意元组、列表、字典嵌套
cmp 比较的函数,它具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0
key 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序
reverse 排序规则,reverse = True 降序 , reverse = False 升序(默认)

排序方式

cmp 和 key

L=[('b',2),('a',1),('c',3),('d',4)]
sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))  # 利用cmp函数
# [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
sorted(L, key=lambda x:x[1])   # 利用key
# [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

以上引用自菜鸟教程:Python sorted() 函数

多列排序

person_list = [
    {'name':'戚子宇','gender':'1','score1':10,'score2':6,'score3':5},
    {'name':'小明','gender':'0','score1':10,'score2':12,'score3':12},
    {'name':'小蓝','gender':'0','score1':8,'score2':9,'score3':16},
    {'name':'小黑','gender':'0','score1':10,'score2':12,'score3':20},
]
# 指定某列排序
sorted(person_list, key=lambda person:person['score1'],reverse=True)
# 指定多列排序,score1相同按照score2排序,优先级从前往后,越来越小
sorted(person_list, key=lambda person:(person['score1'],person['score2']),reverse=True)

# 动态多列排序

排序字段不确定时,动态生成排序字段

score_list = ['score1','score2','score3']
sorted(person_list, key=lambda person:[person[score] for score in score_list],reverse=True)

注意:sorted函数会返回一个新的list

相关文章

网友评论

      本文标题:python sorted多列排序

      本文链接:https://www.haomeiwen.com/subject/tsphcctx.html