實際案例
某班英語成績以字典形式存儲爲{‘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)]