某班英语成绩以字典形式存储为{‘Li’:79, ‘Jim’:88, ‘Lucy’:92, …},根据成绩高低,计算学生排名。
这里我们将利用内置函数sorted对学生的英语成绩排名。
首先,我们利用zip()将字典转化为元组;然后,我们调用sorted函数对元组进行排序,代码如下:
# -*- coding: utf-8 -*-
from random import randint
student = {k: randint(0, 100) for k in "qazwsx"}
# 将字典转为元组
stu = zip(student.values(), student.keys())
print sorted(stu)
其运行结果如下:
[(1, 'x'), (3, 's'), (40, 'w'), (41, 'a'), (78, 'q'), (90, 'z')]
我们利用sorted函数中key这个参数,对字典进行排序。看到这里有没有想起我们上一篇文章中根据值对字典的元素进行从大到小的排序呢?不错,这里我们将使用上一篇文章所使用的方法对字典排序,代码如下:
# -*- coding: utf-8 -*-
from random import randint
student = {k: randint(0, 100) for k in "qazwsx"}
print sorted(student.items(), key=lambda v: v[1])
其运行结果如下:
[('x', 1), ('s', 3), ('w', 40), ('a', 41), ('q', 78), ('z', 90)]
简书个人主页:http://www.jianshu.com/u/766a46e00f6b