重新排列文件

时间:2015-12-16 23:33:41

标签: python file

我有一段代码(如下所示),这使我能够向学生提出一系列随机问题,然后将他们的姓名和分数保存到文件中。我将名称和分数合并为一个名为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")

2 个答案:

答案 0 :(得分:1)

sorted key函数可以为您执行此操作,但如果您没有将它们组合成单个字符串,那么它会更好,但存储{相反,{1}}对。使用tuple很好地概括。而不是存储:

operator.itemgetter

存储

score = str(score)
Info = Name + " " + score

然后当你需要排序时,执行:

Info = (Name, score)  # Score remains a float

在您提供的代码中,您正在写入文件并回读(需要重新分析),因此您可能需要查看# Imports at top of file, not each sort from operator import itemgetter ... for name, score in sorted(myunorderedinfo, key=itemgetter(1, 0)): 模块以正确格式存储对({1}}简单的空间分离很容易搞乱);在这种情况下,您必须将输入转换回csv,因为float会传回csv.reader的{​​{1}},但相对来说使用简单的生成器表达式(左侧作为练习)很容易。

答案 1 :(得分:0)

顺便说一句,你可以通过删除所有重复的代码来使你的代码更整洁:

VALID_CLASS_NAMES = {"A", "B", "C"}

if Classresults not in VALID_CLASS_NAMES:
    print("Invalid class results selection")
    raise Exception("BOOM")

filename = "Class {} Results.txt".format(Classresults)
with open(filename, "r") as class_results_file:
    alphabet=class_results_file.readlines()
    for line in sorted(alphabet):
        print(line)

现在,如果您添加“D”类,则只需将其添加到有效类名称集中。