如何存储最后三个分数

How to store last three scores

我最近在做一个关于学校数学测验的学校项目。我成功地完成了项目的三个任务中的两个。不过第三个任务好像挺难的。

我目前正在尝试存储该学生的最后三个分数。但是我不能完全让它工作。我确实看过这个线程:。但是我的 for:

代码有错误
scores = file.readlines()

这给了我一个错误,说它不可读。很遗憾,我无法使该代码正常工作。

所以我想做的是对学生的最后三个分数进行评分。然后如果多于 3,那么我想删除最近的分数。

这是我的代码:

import random
import csv
import operator
import os.path
import sys

user_scores = {}

validclass = "No"
classfile = "Class"
studentteacher = "None"

while studentteacher == "None":
    studentteacherinput = input("Are you a Teacher or a Student?")

if studentteacherinput == "Teacher":
        studentteacher = "Teacher"
        print(studentteacher)
    elif studentteacherinput == "Student":
        studentteacher = "Student"
        print(studentteacher)
    else:
        print("Please enter the one applicable ' Student ' or ' Teacher '.")

while validclass == "No":

    pupilclass = input("What class are you in or what class would you like to see??")
    print(pupilclass)

    if pupilclass == "1":
        if os.path.exists("class1scores.txt") and studentteacher == "Teacher":
            file = open("class1scores.txt", "r")
            validclass = "Yes"
        elif os.path.exists("class1scores.txt") and studentteacher == "Student":
            file = open("class1scores.txt", "a")
            classfile = "class1scores.txt"
            validclass = "Yes"
        else:
            file = open("class1scores.txt", "w")
            validclass = "Yes"

    elif pupilclass == "2":
        if os.path.exists("class2scores.txt") and studentteacher == "Teacher":
            file = open("class2scores.txt", "r")
            validclass = "Yes"
        elif os.path.exists("class2scores.txt") and studentteacher == "Student":
            file = open("class2scores.txt", "a")
            classfile = "class2scores.txt"
            validclass = "Yes"
        else:
            file = open("class1scores.txt", "w")
            validclass = "Yes"

    elif pupilclass == "3":
        if os.path.exists("class3scores.txt") and studentteacher == "Teacher":
            file = open("class3scores.txt", "r")
            validclass = "Yes"
        elif os.path.exists("class3scores.txt") and studentteacher == "Student":
            file = open("class3scores.txt", "a")
            classfile = "class3scores.txt"
            validclass = "Yes"
        else:
            file = open("class1scores.txt", "w")
            validclass = "Yes"

file.seek(0)
scores = file.readline()

if studentteacher == "Teacher":
    teacherinput = input("How would you like to sort the list? ' Alphabetically ' to sort it alphabetically with the students highest score, ' Highest ' for the highest scores with highest to lowest or ' Average ' for average scores with highest to lowest")

    if teacherinput == "Alphabetically":
        print("alphabetically")
        csv1 = csv.reader(file, delimiter = ",")
        sort = sorted(csv1, key = operator.itemgetter(0))

        for eachline in sort:
            print(eachline)

        sys.exit()

    if teacherinput == "Highest":
        print("Highest")

    if teacherinput == "Average":
        print("Average")

namecheck = "invalid"

while namecheck == "invalid":
    name = input("Please enter your name?")
    if name.isalpha():
        print("Your name is valid.")
        namecheck = "valid"
        #file.write(name + ",")
    else:
        print("Please enter a valid name, only containing letters.")

operation = input("Hello %s! Would you like to do Addition, Subtraction or Multiplication" % (name))

score = 0

if operation == "Addition":
    for i in range(0, 10):
        number1 = random.randint(1, 20)
        number2 = random.randint(1, 20)
        answer = number1 + number2
        question = input("What is " + str(number1) + " + " + str(number2))

        if question.isdigit() == True:
            int(question)
        else:
            question = input("Please enter a answer with digits only. What is " + str(number1) + " + " + str(number2))

        if int(question) == answer:
            score += 1
            print("Correct!")
        else:
            print("Wrong!")

elif operation == "Subtraction":
    for i in range(0, 10):
        number1 = random.randint(1, 20)
        number2 = random.randint(1, 20)
        answer = number1 - number2
        if number2 >= number1:
            answer = number2 - number1
            question = input("What is " + str(number2) + " - " + str(number1))
        else:
            question = input("What is " + str(number1) + " - " + str(number2))

        if question.isdigit() == True:
            int(question)
        else:
            if number2 >= number1:
                answer = number2 - number1
                question = input("Please enter a positive answer with digits only. What is " + str(number2) + " - " + str(number1))
            else:
                question = input("Please enter a positive answer with digits only. What is " + str(number1) + " - " + str(number2))

        if int(question) == answer:
            score += 1
            print("Correct!")
        else:
            print("Wrong!")

elif operation == "Multiplication":
    for i in range(0, 10):
        number1 = random.randint(1, 20)
        number2 = random.randint(1, 20)
        answer = number1 * number2
        question = input("What is " + str(number1) + " x " + str(number2))

        if question.isdigit() == True:
            int(question)
        else:
            question = input("Please enter a answer with digits only. What is " + str(number1) + " + " + str(number2))

        if int(question) == answer:
            score += 1
            print("Correct!")
        else:
            print("Wrong!")



print("Your final score is %s/10, Well Done!" % (score))
#file.write(str(score) + "\n")

#This is the code which I was trying to use to get the last 3 scores.
user_scores = {}
for line in scores:
    name, score = line.rstrip('\n').split(',')
    score = int(score)
    if name not in user_scores:
        user_scores[name] = []       # Initialize score list
    user_scores[name].append(score)  # Add the most recent score
    if len(user_scores[name]) > 3:
        user_scores[name].pop(0)     # If we've stored more than 3, get rid of the oldest

file.close()

抱歉,方法效率低下,但这正是我喜欢的思考方式。感谢您抽出时间。

#This is the code which I was trying to use to get the last 3 scores.
user_scores = {}
for line in scores:
    name, score = line.rstrip('\n').split(',')
    score = int(score)
    if name not in user_scores:
        user_scores[name] = []       # Initialize score list
    user_scores[name].append(score)  # Add the most recent score
    if len(user_scores[name]) > 3:
        user_scores[name].pop(0)     # If we've stored more than 3, get rid of the oldest

所以我从上面提到的 link 中提取了它。我的目标是尽量只拿三分,不超过三分。

如您所知,有不同的模式可以让您 open()(2/3) 一个文件。如果您使用 "a""w",您可以' 从文件中读取。不过,您也可以添加 "+",以允许阅读:

open("file.txt","a+")

此外,我不确定您使用的 Python 是哪个版本,但是 file() 是 Python 2 中的内置类型和函数,因此您应该如果这是您使用的版本,请不要将其用作变量名。

实施队列 - https://docs.python.org/2/library/collections.html#collections.deque

from collections import deque

for line in scores:
    name, score = line.rstrip('\n').split(',')
    score = int(score)
    if name not in user_scores:
        user_scores[name] = deque(maxlen=3)
    temp_q = user_scores[name]
    temp_q.append(str(score))
    user_scores[name] = temp_q

现在 user scores 是一个 dict,以 key 作为名称,values 作为 deque 对象,只有 3 个分数。您需要遍历它们,将队列转换为列表并加入元素以将它们写入文件。

filehandle = open('outputfile.csv' ,'w')
for key, values in user_scores.iteritems():
    filehandle.write(name + ',')
    filehandle.write(','.join(list(values)) + '\n')

filehandle.close()