2016-12-01 58 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:感謝您的注意。編輯後... –