在数字上对测验分数进行排序时出错

时间:2015-07-07 08:28:58

标签: python

对于我的课程作业,我一直在尝试以数字方式对得分文件进行排序并将其打印到python

我已经尝试从stackoverflow到我的代码实现其他答案,但没有成功。

这是我的代码:

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)

1 个答案:

答案 0 :(得分:0)

您正在打开该文件并将其引用放在f中,然后您将f更改为指向空字典。 (在以下行中) -

 with open(filename) as f:
     f = {}

所以分数总是空的,你永远不会得到任何印刷品。

我相信你应该将diciotnary变量的名称更改为其他名称,然后在打开文件后,你应该读取它并将值放在字典中。我们不知道您的文件是如何构建的,因此我们无法帮助您。

另外,你在其他地方做类似的事情,你应该避免做这类事情 -

with open(filename, 'a') as f:
    f = open(filename, "r")

另外,当您在以下行中写入文件时,另一个建议是

f.write(str(name) + str(score) + '\n')

你没有在你的名字和分数之间加上任何分隔符,你应该在那里放置某种分隔符,以便在阅读时你可以很容易地得出名称和分数。要使用的标准分隔符为comma - ','