实际案例
某编程竞赛系统,对于参赛选手解题情况进行计时。
选手完成题目后,就将该选手解题用时记录到字典中,
以便赛后按选手名次查询成绩
{'Lilei':(2,43),'HanMeimei':(5,52),'Jim':(1,39)}
比赛结束后,需要按照排名次序依次打印选手成绩,如何实现。
普通方法:
d = {}
d['Jim'] = (1,35)
d['Leo'] = (2,37)
d['Bob'] = (3,40)
for k in d:print k
由结果可以发现默认数据结构dict,没有顺序
解决方案:
使用collections.OrderedDict
以OrderedDict代替内置字典dict,依次将选手成绩存入OrderedDict
from collections import OrderedDict
d2 = OrderedDict()
d2['Jim'] = (1,35)
d2['Leo'] = (2,37)
d2['Bob'] = (3,40)
for k in d2:print k
编程模拟竞赛系统:
from time import time
from random import randint
from collections import OrderedDict
d = OrderedDict()
palyers = list('abcdefg')
start = time()
# print start
for i in xrange(7):
# 延时
raw_input()
# 每次随机选取一名选手答题完毕
p = palyers.pop(randint(0, 6 - i))
end = time()
print i + 1,p, end - start
d[p] =(i+1,end-start)
#比赛结束打印成绩
# 打印换行
print
# 打印分隔符
print '-'*20
for k in d:
print k,d[k]
网友评论