我有一段代碼(見下文),它使我能夠問學生一系列隨機問題,然後將他們的名字和分數保存到一個文件中。我把名字和分數合併成一個名爲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'會更好。 –