编程实现学生成绩排序
2022-01-23 本文已影响0人
花开有声是我
有一个文件记录了学生考试成绩,每行内容为姓名和分数,原始文件不对齐,且存在空格或空行,如下图
Student test scores.png
请用编程实现,将所有人的成绩排序写入到一个新文件,成绩从高往低排序,姓名靠左对齐,分数靠右对齐,如下图:
Student test scores.png
file = open(r"C:\Users\Administrator\Desktop\studentscore.txt", "r")
file1 = open(r"C:\Users\Administrator\Desktop\studentscore_20220123.txt", "a")
def bubbleSort(my_list, names):
size = len(my_list)
for i in range(size):
for j in range(size):
if my_list[i] > my_list[j]:
tmp = my_list[i]
my_list[i] = my_list[j]
my_list[j] = tmp
tmp_name = names[i]
names[i] = names[j]
names[j] = tmp_name
names = []
scores = []
list1 = file.readlines()
for n in list1:
if n != "\n":
list1 = n.split(";")
for str1 in list1:
list2 = str1.split(":")
key = list2[0].strip()
value = list2[1].strip()
if key == "name":
names.append(value)
if key == "score":
scores.append(int(value))
bubbleSort(scores, names)
student_info = ["name", "score"]
for idx, n in enumerate(names):
str1 = student_info[0] + ":" + n + "\t" + ";" + student_info[1] + ":" + str(scores[idx]).rjust(6) + "\n"
file1.write(str1)
file1.close()
file.close()