2016-12-01 59 views
0

我无法通过数值对我的.txt文件进行排序。我附上了代码,并试图让它按分数排序, 我也无法将它打印到txt文件的新行中。如何用数字排序.txt文件

def Highscore(): 
    name = input("What is your name for the scoreboard?") 
    newhighscore =(name, highscore) 
    newline = ("\n") 
    HighscoreWrite = open ("highscore.txt", "a") 
    HighscoreWrite.write(highscore) 
    HighscoreWrite.write(name) 
    HighscoreWrite.write("\n") 
    HighscoreWrite.close() 
    HighscoreRead = open("highscore.txt", "r") 
    ordered = sorted(HighscoreRead) 


    print (ordered)  



    print (HighscoreRead.read()) 
    #print (newhighscore) 
    HighscoreRead.close() 
retry = "Yes" 
while retry == "Yes": 
    print ("Welcome to this quiz.\n") 
    score = 0 
    attempt = 0 
    while score < 10: 
     correct = Question() 
     if correct: 
      score += 1 
      attempt += 1 
      print ("Well done, You got it right") 
     else: 
      print ("Good try but maybe next time") 
      attempt += 1 
    highscore = score, ("/") ,attempt 
    highscore = str(highscore) 
    message = print ("You scored", (score), "out of ",(attempt)) 
    Highscore(); 
    retry = input("Would you like to try again? Yes/No") 
+0

读取所有数据,将文本转换为int然后对其进行排序。或者在'sorted()'中使用'key ='参数 – furas

回答

1

为了数字排序文件,你必须创建一个key(line)函数,接受行参数,并返回分数的数值。

假设highscore.txt就是每一行的数值,随后以空格开始的文本文件,该key功能可能是:

def key_func(line): 
    return int(line.lstrip().split(' ')[0]) 

然后可以使用ordered = sorted(HighscoreRead, key = key_func)

因为它是一个单线函数,你也可以使用一个lambda:

ordered = sorted(HighscoreRead, key= (lambda line: int(line.lstrip().split(' ')[0]))) 
+0

为了清晰和Python 2的兼容性,键应该被指定为关键字参数。此外,lambda周围的额外括号使其更加令人困惑 - 例如:最后错过了一个。 –

+0

@AlexHall:感谢您的注意。编辑后... –