我最近一直在做一个关于学校数学测验的学校项目。我成功地完成了我项目的三个任务中的两个。然而,第三项任务似乎相当困难。
我目前正试图存储该学生的最后三个分数。但是我无法让它发挥作用。我确实看过这个帖子:Displaying only the highest of a person's 3 most recent scores, saved in a .txt file。但是我的代码中出现了错误:
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
所以我从上面提到的链接中获取了它。我的目标是尝试只获得三个分数,而不是超过3分。
答案 0 :(得分:1)
您似乎知道,您可以open()
(2 / 3)文件中的不同模式。如果您使用"a"
或{{1} },你无法从文件中读取。您也可以添加"w"
以允许阅读:
"+"
另外,我不确定您使用的是哪个版本的Python,但是file()
是Python 2中的内置类型和函数,因此如果是的话,您不应该将它用作变量名称你正在使用的版本。
答案 1 :(得分:-1)
实施队列 - 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
现在,用户分数是一个带有键作为名称的dict,值是一个只有3个分数的双端队列对象。您需要遍历它们,将队列转换为列表并加入元素以将它们写入文件。
filehandle = open('outputfile.csv' ,'w')
for key, values in user_scores.iteritems():
filehandle.write(name + ',')
filehandle.write(','.join(list(values)) + '\n')
filehandle.close()