首先,我需要随机生成一个班级20人的成绩,语文,数学,英文,满分100,最低分0 任务是:按照总分进行排序,从高到低,总分相同以数学成绩为主,都相同则以学号。
随机生成学生的数据
import random
#学号以 1001
print(random.randint(0,100)) #随机生成[0,100]之间的任意一个整数
chinese_names = [
"张三", "李四", "王五", "赵六", "孙七", "孙八", "王九", "赵十",
"钱十一", "赵十二", "陈十三", "孙十四", "李十五", "周十六", "吴十七",
"王十八", "赵十九", "赵二十", "赵二十一", "赵二十二", "赵二十三",
"赵二十四", "赵二十五", "赵二十六", "赵二十七", "赵二十八", "赵二十九",
"赵三十", "赵三十一", "赵三十二", "赵三十三", "赵三十四", "赵三十五"
]
# print(random.sample(chinese_names, 20))
name_list = random.sample(chinese_names, 20) #随机选取20个名字
f = open('score.txt', w)
for i in range(20):
ID = '100' + str(i)
name = name_list[i]
english = random.randint(0,100)
math = random.randint(0,100)
chinese = random.randint(0,100)
f.write( '%s,%s,%d,%d,%d' %(ID,name,english,math,chinese) )
f.colse()
排序代码
import random
f = open('score.txt', 'r')
lines = f.readlines()
result = []
for line in lines :
id, name, eng , math, chi = line.split(',')
dic = {}
dic['id'] = int(id)
dic['name'] = name
dic['english'] = eng
dic['math'] = math
dic['chinese'] = chi
dic['total'] = int(eng) + int(math) + int(chi)
result.append(dic)
f.close()
result.sort(key = lambda x : -x['total'] )
f1 = open('report.txt', "w")
for info in result:
f1.write('%5s,%-8s,%5s,%5s' % (info['id'], info['name'], info['total'], info['math']))
f1.write('\n')
f1.close()
—— 本文来自火龙信奥(义乌睿码科技):义乌青少年信息学奥赛与编程教育平台,专注 CSP-J/S、NOIP、GESP 竞赛培训,线上线下融合教学,助力编程升学。网址:hlcoding.com