我有一段代码(见下文),它使我能够问学生一系列随机问题,然后将他们的名字和分数保存到一个文件中。我把名字和分数合并成一个名为info的变量,名字首先是分数。我现在需要按照评分顺序对这些信息进行分类。是否有一种方法让我在整个文件中暂时将分数放在名称的前面,以便我可以使用已排序的函数使其从最低到最高?重新排列文件
任何帮助将不胜感激!谢谢。
import random
import time
Name=input("What is your name?")
Class=input("Are you in Class A, B or C?")
print("Welcome" ,Name, "to the Maths Quiz!!")
time.sleep(3)
QuestionNumber=0
Operations=["+","-","x"]
answer=0
score=0
while QuestionNumber < 10:
Num1=random.randint(1,12)
Num2=random.randint(1,12)
QuestionNumber=QuestionNumber+1
operation = random.choice(Operations)
print("What is", Num1 ,operation, Num2)
guess=int(input("What is the answer to this question?"))
if operation =="+":
answer=Num1+Num2
elif operation =="-":
answer=Num1-Num2
elif operation =="x":
answer=Num1*Num2
if guess==answer:
score=score+1
print ("Correct")
else:
print("Incorrect")
print("Well done You got", score, "Out of 10!!")
score=str((score))
Info= (Name + (" ") + score)
if Class=="A":
ClassA=open("Class A Results.txt","a")
ClassA.write(Info)
ClassA.write(" \n")
ClassA.close()
elif Class=="B":
ClassB=open("Class B Results.txt","a")
ClassB.write(Info)
ClassB.write(" \n")
ClassB.close()
elif Class=="C":
ClassC=open("Class C Results.txt","a")
ClassC.write(" \n")
ClassC.write(Info)
ClassC.close()
Viewscores=input("Do you want to see previous scores? Y/N")
if Viewscores=="Y":
Classresults=input("Which Class would you like to see the results of?")
else:
print ("Thank you for using the maths quiz, press enter to close the program in 10 seconds")
time.sleep(10)
closeprogram=input("Hit enter")
if Classresults=="A":
ClassA=open("Class A Results.txt","r")
Class=Class
alphabet=ClassA.readlines()
for line in sorted(alphabet):
print(line)
elif Classresults=="B":
ClassB=open("Class B Results.txt","r")
Class=ClassB
alphabet=ClassB.readlines()
for line in sorted(alphabet):
print(line)
elif Classresults=="C":
ClassC=open("Class C Results.txt","r")
Class=ClassC
alphabet=ClassC.readlines()
for line in sorted(alphabet):
print(line)
else:
print ("That is not valid")
阅读https://wiki.python.org/moin/HowTo/Sorting#Key_Functions –
另外,不要将变量命名为'Class'(它非常接近内置的'class'关键字,并避免通用变量名称,比如'Name' - 类似'pupil_name'会更好。 –