案例
某编程竞赛系统,对参赛选手编程解题进行计时,选手完成题目后,把该选手解题时用时记录到字典中,以便赛后按选手名查询成绩,(答题用时越短,成绩越优)
{'LiLei':(2, 43), 'HanMeimei':(5, 52), 'Jim':(1, 39)...}
比赛结束后,需按排名顺序依次打印选手成绩,如何实现?
解析
(1)collections.OrderedDict
d = {}
d["Jim"] = (1, 35)
d["Leo"] = (2, 37)
d["Bob"] = (3, 40)
print(d) # 乱序
# collections.OrderedDict
from collections import OrderedDict
from time import time
from random import randint
d1 = OrderedDict()
d1["Jim"] = (1, 35)
d1["Leo"] = (2, 37)
d1["Bob"] = (3, 40)
print(d1) # 有序
res = OrderedDict()
players = list('ABCDEFGH')
start = time()
for i in range(8):
input()
p = players.pop(randint(0, 7-i)) # 随机移除一位
end = time()
print(i+1, p, end-start)
res[p] = (i+1, end-start)
print('-'*80) # 分隔符
for k in res:
print(k, res[k])