如何添加带有名称的有序分数表

2024-05-28 19:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

import random
number_correct = 0

def scorer():
    global number_correct
    if attempt == answer:
        print("Correct.")
        number_correct = number_correct + 1
    else: 
        print('Incorrect. The correct answer is ' + str(answer))

name = input("Enter your name: ")

for i in range(10):
    num1 = random.randrange(1, 100)
    num2 = random.randrange(1, 100)
    operation = random.choice(["*", "-", "+", "%", "//"])
    print("What is the answer?", num1, operation, num2)
    attempt = int(input(" "))
    if operation == "+":
        answer = num1 + num2
        scorer()
    elif operation == "-":
        answer = num1 - num2
        scorer()
    elif operation == "*":
        answer = num1 * num2
        scorer()
    elif operation == "%":
        answer = num1 % num2
        scorer()
    elif operation == "//":
        answer = num1 // num2
        scorer()
print(name + ", you got " + str(number_correct) + " out of 10.")

我已经做了上面的测验,现在想让它做一个高分表,从最高到最低的名字和分数挨在一起。你知道吗

我试着先对分数进行排序,这就是我得出的结论:

scores = []
names = []
file = open("scores.txt","a")
addedline = number_correct
file.write('%d' % addedline) 
file.close()
file = open("scores.txt","r")
for eachline in file:
    scores.append(eachline)
    x = scores.sort()
    print(x)
file.close()

我不认为这是可行的,我不知道我将如何结合在最后的名字和分数(确保正确的分数是旁边的正确的名字)。请帮忙。 谢谢


Tags: answernamenumberrandom名字operation分数file
2条回答

我建议将姓名和分数存储为csv,然后您可以用分数读取姓名,然后用分数作为键进行排序。你知道吗

with open("scores.txt", "a") as file:
    file.write("%s, %s\n" % (name, number_correct))
with open("scores.txt", "r") as file:
    data = [line.split(", ") for line in file.read().split("\n")]

data = sorted(data, key = lambda x: -int(x[1]))

print("\n".join(["%s\t%s" % (i[0], i[1]) for i in data]))

我不确定你的文本文件到底是什么样子的,但我建议你使用字典(只要你没有相同的分数超过一次)。像这样,你可以把键作为你的分数,值可以是名字,字典会自动按键的顺序排序。你知道吗

相关问题 更多 >

    热门问题