Python 对测验分数进行数字排序时出错
在我的课程作业中,我一直在尝试对分数文件进行数字排序,并将其打印到python中 我曾尝试在代码中实现stackoverflow的其他答案,但没有成功 这是我的代码:Python 对测验分数进行数字排序时出错,python,Python,在我的课程作业中,我一直在尝试对分数文件进行数字排序,并将其打印到python中 我曾尝试在代码中实现stackoverflow的其他答案,但没有成功 这是我的代码: if sortmethod == ("n"): with open(filename) as f: f = {} scores=[] for name, v in f.items(): scores.append((name, score))
if sortmethod == ("n"):
with open(filename) as f:
f = {}
scores=[]
for name, v in f.items():
scores.append((name, score))
for name, score in sorted(scores, key=lambda a: a[1], reverse=True):
print(name, scores)
谢谢你的帮助
完整代码(如果需要):
import random
import operator
OPERATIONS = [
(operator.add, "+"),
(operator.mul, "*"),
(operator.sub, "-")
]
NB_QUESTIONS = 10
def get_int_input(prompt=''):
while True:
try:
return int(input(prompt))
except ValueError:
print("Not a valid input (integer is expected)")
def get_bool_input(prompt=''):
while True:
val = input(prompt).lower()
if val == 'yes':
return True
elif val == 'no':
return False
else:
print("Not a valid input (yes/no is expected)")
if __name__ == '__main__':
name = input("What is your name?").title()
class_name = input("Which class do you wish to input results for? ")
print(name, ", Welcome to the OCR Controlled Assessment Maths Test")
score = 0
for _ in range(NB_QUESTIONS):
num1 = random.randint(1,25)
num2 = random.randint(1,25)
op, symbol = random.choice(OPERATIONS)
print("What is", num1, symbol, num2)
if get_int_input() == op(num1, num2):
print("Correct")
score += 1
else:
print("Incorrect")
print("Well done", name, "you scored", score, "/", NB_QUESTIONS)
filename = class_name + ".txt"
with open(filename, 'a') as f:
f.write(str(name) + str(score) + '\n')
sortmethod = input("How do you wish to sort the scores. A = Alphabetically N = Numerically").lower()
if sortmethod == ("a"):
with open(filename, 'a') as f:
f = open(filename, "r")
lines = [line for line in f if line.strip()]
f.close()
lines.sort()
if sortmethod == ("n"):
with open(filename) as f:
f = {}
scores=[]
for name, v in f.items():
scores.append((name, score))
for name, score in sorted(scores, key=lambda a: a[1], reverse=True):
print(name, scores)
您正在打开文件并将对它的引用放入
f
中,然后将f
更改为指向一个空字典。(在以下行中)-
所以分数总是空的,你永远不会得到任何打印出来的东西
我认为您应该将双二进制变量的名称更改为其他名称,然后在打开文件后,您应该读取它并将值放入字典中。我们不知道您的文件是如何构造的,因此我们无法在这方面帮助您
另外,你在其他地方做类似的事情,你应该避免做这样的事情-
with open(filename, 'a') as f:
f = open(filename, "r")
另外,另一个建议是,当您在以下行中写入文件时-
f.write(str(name) + str(score) + '\n')
你没有在你的名字和分数之间加上任何分隔符,你应该在那里加上某种分隔符,这样当你回过头来阅读时,你就可以很容易地辨认出名字和分数。要使用的标准分隔符是逗号-','
f.write(str(name) + str(score) + '\n')