如何在Python中打印保存在文本文件中的高分

时间:2015-09-24 19:12:30

标签: python dictionary io

我已经创建了一个策划游戏,作为今年晚些时候某些课程作业的一部分,我希望能够打印高分和它所属的人的名字。每当一个人赢得比赛。我已经成功地保存了输入的用户名和他们的分数,但我尝试打印高分天堂。这是我到目前为止所做的所有代码,如果我写的任何内容完全错误或效率低下,我会道歉,我对python来说还是比较新的。

from random import randrange
import time
import operator
guesses=0
score=0
totaltime=0
correctlist=[]
nonexactscore=0
#Initiates variables
print("Enter a username")
while 1==1:
    username=input()
    namelist=list(username)
    if " " not in namelist:
        username=username.upper()
        break
    else:
        print("Cannot enter spaces in your username")
print("Enter difficulty- 'EASY' , 'NORMAL' or 'HARD")
while 1==1:
    difficulty=input()
    if difficulty == "EASY" or difficulty == "NORMAL" or difficulty ==    "HARD":
        break
    else:
        print("Invalid input")
#Waits for user input to be valid (EASY , NORMAL or HARD) 
if difficulty=="HARD":
    Numberlength=5
#Sets the length of the number to be guessed to 5 if the difficulty = hard
else:
    Numberlength=4
#Otherwise sets the length of the number to be guessed to the normal length of 4
for n in range(0,Numberlength):
    correctlist.append(str(randrange(0,9)))
#Creates a list of length Numberlength made from a sequence of random     numbers (In string format)
while score != Numberlength:
#Continuously asks for the guess while it is incorrect (For it to be     correct, the score must = the numberlength)
    temptime=0
    nonexactscore=0
    score=0
    guess=0
    print("enter guess")
    print(correctlist) #For debugging
    temptime=int(time.time())
#initiates the timer
    while 1==1:
        guess=str(input())
        if len(guess)==Numberlength and guess.isdigit():
            break
#Validates input
        else:
            print("Invalid input")
    for n in range(0,Numberlength):
        if guess[n]==correctlist[n]:
            score+=1
#Increments score variable if pairs of numbers in the guess list and the correct list match
            if difficulty == "EASY":
                print("You got a match in place " + str(n+1))
#Prints the position of the correct guess if the difficulty = easy
    if guess[n] in correctlist and guess[n] != correctlist[n]:
        nonexactscore += 1
#Increments non-exact score variable if the guess appears in the correctlist     but isn't an exact match
    print("Number of exact matches: " + str(score) + " Number of non-exact matches: " + str(nonexactscore) )
#Prints your score and non-exact score
    if score != Numberlength:
        print("Incorrect, try again!")
    guesses+=1
#Increments guesses variable every time you make an incorrect guess
    totaltime+=int(time.time())-temptime
#Adds the time taken for an individual guess to the totaltime
else:
    print("Guesses: " + str(guesses))
    print("You win!")
    print("You took " + str(totaltime) + " Seconds! ")
    totalscore=int(1000*(1/(float(totaltime*guesses))))
    print("Score for comparison:" + str(totalscore))
    with open("mastermindscores.txt","a") as f:
        f.write(username + " " + str(totalscore)+ "\n")
    with open("mastermindscores.txt","r") as k:
        scoredict={}
        for line in k:
            key,val = line.split(" ")
            scoredict[key]=val
    print(scoredict) #for debugging
        print("High score: " + max(scoredict) + " " +     str(scoredict.get(max(scoredict))))
#Prints information about your victory

此代码导致txt文件看起来像这样:

    NAME 1000
    OTHERNAME 10000
    ANOTHERNAME 100000

我正在寻找打印的节目"高分:ANOTHERNAME 100000"但目前我无法确定它如何决定打印的名称(因为在几场比赛之后,它并没有打印出高分)

非常感谢任何有关编码的建议或我对该计划所做的任何改进,谢谢。

另外,如果您需要进一步澄清,我会在几个小时左右的时间内查看这篇文章。

1 个答案:

答案 0 :(得分:4)

print("High score: " + max(scoredict) + " " +     str(scoredict.get(max(scoredict))))

在字典上使用时,max会选择最高的密钥。您的密钥是字符串,因此它选择具有最高字典顺序的用户名;换句话说,按字母顺序排列的名称。

>>> max({"Kevin": 99999, "Zane": 23})
'Zane'

如果要查找最高值,请尝试:

>>> d = {"Kevin": 99999, "Zane": 23}
>>> max_name = max(d, key=lambda k: d[k])
>>> max_name
'Kevin'
>>> d[max_name]
99999

当然,这假设得分词典中的值是数字。如果它们是字符串,你就会再次出现字典排序问题。

>>> d = {"Kevin": "100000", "Zane": "2"}
>>> max(d, key=lambda k: d[k])
'Zane'

因此,请务必在阅读文件时将值转换为正确的类型。

with open("mastermindscores.txt","r") as k:
    scoredict={}
    for line in k:
        key,val = line.split(" ")
        scoredict[key]=int(val)