案例1:
某班語文科目的成績以字典形式儲存,形式為:{"lili":89,"wenwen":91 ...}
根據成績高低,計算學生的排名
解決方案:
使用內建函式sorted
1,利用zip將字典資料轉化為元組
2,傳遞sorted函式的key引數
# eg_v1 利用zip將字典資料轉化為元組
from random import randint stud = {x:randint(60,100) for x in "abcdefghjk"} # 建立隨機的成績單字典 print(stud) # {'a': 89, 'b': 87, 'd': 83, 'j': 97, 'e': 74, 'f': 75, 'h': 97, 'g': 61, 'c': 62, 'k': 90} print(stud.keys()) # 得到字典的鍵 # dict_keys(['a', 'b', 'd', 'j', 'e', 'f', 'h', 'g', 'c', 'k']) print (stud.values()) # 得到字典的值 # dict_keys(['a', 'b', 'd', 'j', 'e', 'f', 'h', 'g', 'c', 'k']) z = zip(stud.values(),stud.keys()) print (sorted(z)) # [(61, 'g'), (62, 'c'), (74, 'e'), (75, 'f'), (83, 'd'), (87, 'b'), (89, 'a'), (90, 'k'), (97, 'h'), (97, 'j')]
# eg_v2 傳遞sorted函式的key引數
from random import randint rest = {x:randint(60,100) for x in "abcdefghjk"} # 建立隨機的成績單字典 print (rest) # {'h': 96, 'j': 95, 'b': 97, 'g': 78, 'f': 64, 'k': 81, 'd': 72, 'e': 69, 'c': 93, 'a': 61} print (rest.items()) # dict_items([('h', 96), ('j', 95), ('b', 97), ('g', 78), ('f', 64), ('k', 81), ('d', 72), ('e', 69), ('c', 93), ('a', 61)]) result = sorted(rest.items(),key = lambda x:x[1]) print (result) # [('a', 61), ('f', 64), ('e', 69), ('d', 72), ('g', 78), ('k', 81), ('c', 93), ('j', 95), ('h', 96), ('b', 97)]