[Python] dict字典排序和多条件排序

 

利用lambda实现排序;要实现多条件排序,只需要依次指定排序的标准,具体实现如下

counter = {'': 1, '不是': 1, '': 3}

counter_list = sorted(counter.iteritems(), key=lambda x: x[1], reverse=True) # 根据value的大小排序
# [('你', 3), ('是', 1), ('不是', 1)]

counter_list = sorted(counter.iteritems(), key=lambda x: (x[1], len(x[0])), reverse=True)  # 多条件排序:(1)value的大小;(2)key的长度
# [('你', 3), ('不是', 1), ('是', 1)]

 

posted @ 2018-01-23 14:11  焦距  阅读(1072)  评论(0编辑  收藏  举报