0

I am making a high-score module, which currently only shows the top 5 scores achieved, i want to be able to show these scores as i am currently but also show them with the name that is associated with that score, how would i do this?

This is my code so far:

def highscore():


   file_highscore = open('scores_test2.txt' , 'r')
   scores_and_names = []
   scores = []
   scores_2 = []
   names = []
   for line in file_highscore.readlines():
      score_info = line.split()

      scores_and_names.append(line)
      scores_2.append(scores_and_names[line][])

      scores.append(score_info[1])
      names.append(score_info[0])


   scores.sort(key = int)
   scores.sort(reverse = True)



   print('The First 5 Highscores are:')
   for item in scores[:5]:

      print(item)

Any help would be much appreciated as I need to use this code for a school assignment.

  • What have you tried so far? What does a line in 'scores_test2.txt' look like? – Mortz Dec 27 '18 at 12:19
  • Store your highscore as dictionary - see my answer in the dupe [here](https://stackoverflow.com/a/53684733/7505395) - a dictionary is better suited to store key:value items. There are also other ways to store them - see the other answers (Json,Pickle,...) – Patrick Artner Dec 27 '18 at 12:24

2 Answers2

0

Here we go

scores = []
with open('scores.txt') as f:
    for line in f:
        name, score = line.strip().split()
        scores.append ((name, int(score)))

    # get top 5
    sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True)

    print('The First 5 Highscores are:')
    for item in sorted_scores[:5]:
        print(item)

scores.txt

John 100
Eduard 200
Phil 150
Romeo 500
Mark 50
Ann 1

Output

('Romeo', 500)                                                                  
('Eduard', 200)
('Phil', 150)                                                                   
('John', 100)                                                                   
('Mark', 50) 
grapes
  • 8,185
  • 1
  • 19
  • 31
0

What you could do is instead of having a list containing the scores, you have a list of tuple with (score, name) and sort it by score.

def highscore():
   file_highscore = open('scores_test2.txt' , 'r')
   scores = []
   for line in file_highscore.readlines():
      score_info = line.split()
      scores.append((score_info[0], int(score_info[1])))

   scores.sort(key = lambda x:x[1], reverse = True)
   print('The First 5 Highscores are:')
   for score, name in scores[:5]:
      print(name, score)
NicoAdrian
  • 946
  • 1
  • 7
  • 18