python字典分别按照key和value升序或者降序排列--以给定一个含有重复元素的数组list,按照其出现次数大小降序输出
对字典采用sorted()函数排序之后的结果是一个list,它包含若干个tuple的元组,第一个是键值,第二个是重复次数
一、从一道面试例题说起:
给定一个数组list为data_in=[1,2,1,2,3,5,1,5,5,1],按照每个元素的出现次数,降序输出
输出格式如下: 元素 个数
1 4
5 3
2 2
3 1
二、实现代码及运行结果如下:
# coding:utf-8
def map_elememt_to_num(data_in):
map_e_to_num={}
for e in data_in:
if e not in map_e_to_num:
map_e_to_num[e]=0
map_e_to_num[e]=1+map_e_to_num[e]
# 对字典采用sorted()函数排序之后的结果是一个list,它包含若干个tuple的元组,第一个是键值,第二个是重复次数:——[(1, 4), (5, 3), (2, 2), (3, 1)]
map_e_to_num_sort_list= sorted(map_e_to_num.items(), key=lambda d:d[1], reverse = True)
print map_e_to_num_sort_list
for e in map_e_to_num_sort_list:
print e[0],"\t",e[1]
data_in=[1,2,1,2,3,5,1,5,5,1]
map_elememt_to_num(data_in)
程序运行结果如下:
[(1, 4), (5, 3), (2, 2), (3, 1)]
1 4
5 3
2 2
3 1
三、其他多值排序介绍:
1. python dict 按照值大小排序
>>> data_in=[1,2,1,2,3,5,1,5,5,1]
>>> print data_in
[1, 2, 1, 2, 3, 5, 1, 5, 5, 1]>>> def map_elememt_to_num(data_in):
... map_e_to_num={}
... for e in data_in:
... if e not in map_e_to_num:
... map_e_to_num[e]=0
...
... map_e_to_num[e]=1+map_e_to_num[e]
... return map_e_to_num
...
>>> print map_elememt_to_num(data_in)
{1: 4, 2: 2, 3: 1, 5: 3}map_elememt_to_num=map_elememt_to_num(data_in)
2. 下面的是按照value的值从大到小的顺序来排序。
map_elememt_to_num_sort= sorted(map_elememt_to_num.items(), key=lambda d:d[1], reverse = True)
>>> print map_elememt_to_num_sort
[(1, 4), (5, 3), (2, 2), (3, 1)]
3.下面的是按照value的值从小到大的顺序来排序。
map_elememt_to_num_sort= sorted(map_elememt_to_num.items(), key=lambda d:d[1], reverse = False)
>>> print map_elememt_to_num_sort
[(3, 1), (2, 2), (5, 3), (1, 4)]
print map_elememt_to_num.iteritems() 得到[(键,值)]的列表。
然后用sorted方法,通过key这个参数,指定排序是按照value,也就是第一个元素d[1]的值来排序。reverse = True表示是需要翻转的,默认(False)是从小到大,翻转的话,那就是从大到小。
4. 对字典按键(key)排序:
map_elememt_to_num_sort= sorted(map_elememt_to_num.items(), key=lambda d:d[0], reverse = False) #d[0]表示字典的键
>>> print map_elememt_to_num_sort
[(1, 4), (2, 2), (3, 1), (5, 3)]
5.同理,可以处理字符串的形式
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[0])
print dict