开发环境:以Python2.x为主 IPython
第四天 : 04day
如何根据字典中值的大小,对字典中的项排序
实际案列:某班6名学生的英语成绩以字典形式存储为:
{'Lilei':79,'Jim':88,'Lucy':92...}
根据成绩高->低,计算学生排名
解决方案:使用内置函数sorted
1.利用zip将字典数据转化元组
In [164]: from random import randint
In [165]: d = {x:randint(60,100) for x in 'xYzAbC'}
In [166]: d
Out[166]: {'A': 91, 'C': 63, 'Y': 80, 'b': 84, 'x': 73, 'z': 63}
In [167]: d
Out[167]: {'A': 91, 'C': 63, 'Y': 80, 'b': 84, 'x': 73, 'z': 63}
In [168]: sorted(d)
Out[168]: ['A', 'C', 'Y', 'b', 'x', 'z']
In [169]: sorted(d,key=str.lower)
Out[169]: ['A', 'b', 'C', 'x', 'Y', 'z']
In [170]: sorted(d,key=str.lower,reverse=True)
Out[170]: ['z', 'Y', 'x', 'C', 'b', 'A']
In [171]: sorted(d,key=str.lower)
Out[171]: ['A', 'b', 'C', 'x', 'Y', 'z']
In [173]: zip(d.itervalues(),d.iterkeys())
Out[173]: [(91, 'A'), (63, 'C'), (84, 'b'), (80, 'Y'), (73, 'x'), (63, 'z')]
In [174]: sort = zip(d.itervalues(),d.iterkeys())
In [175]: sort
Out[175]: [(91, 'A'), (63, 'C'), (84, 'b'), (80, 'Y'), (73, 'x'), (63, 'z')]
In [176]: sorted(sort)
Out[176]: [(63, 'C'), (63, 'z'), (73, 'x'), (80, 'Y'), (84, 'b'), (91, 'A')]
In [185]: sorted(zip(d.itervalues(),d.iterkeys()),reverse=True)
Out[185]: [(91, 'A'), (84, 'b'), (80, 'Y'), (73, 'x'), (63, 'z'), (63, 'C')]
2.传递sorted函数的key参数
In [178]: d.items()
Out[178]: [('A', 91), ('C', 63), ('b', 84), ('Y', 80), ('x', 73), ('z', 63)]
In [179]: d
Out[179]: {'A': 91, 'C': 63, 'Y': 80, 'b': 84, 'x': 73, 'z': 63}
In [180]: d.iteritems()
Out[180]: <dictionary-itemiterator at 0x7f52e0083050>
In [181]: sorted(d.iteritems())
Out[181]: [('A', 91), ('C', 63), ('Y', 80), ('b', 84), ('x', 73), ('z', 63)]
In [182]: sorted(d.iteritems(),key=lambda x:x[1])
Out[182]: [('C', 63), ('z', 63), ('x', 73), ('Y', 80), ('b', 84), ('A', 91)]
In [183]: sorted(d.iteritems(),key=lambda x:x[1],reverse=True)
Out[183]: [('A', 91), ('b', 84), ('Y', 80), ('x', 73), ('C', 63), ('z', 63)]