0

this is my code that imports the file, adds it to a list and sorts the list from highest to lowest:

for x in range (1):
            scoresList = [ ] #this is a variable for the list
            file = open("Leaderboard file.txt", "r") #this opens the file as a read file
            file_line = file.readlines() #this then reads the lines
            scoresList.append(file_line) #this then appends the lines to the list
            file.close()
            leaderboard_list = sorted(scoresList, reverse=True) #this is supposed to order the numbers yet it doesnt seem to do anything
            print(leaderboard_list)
            start_menu()

this is what it prints out:

[['\n', "35['jerry'] 20['bill']15['Dan']20['billy']"]]

and this is the file it is getting the information from:

35['jerry'] 20['bill']15['Dan']20['billy']
benvc
  • 14,448
  • 4
  • 33
  • 54
  • 1
    Hi, welcome to Stack Overflow. You are adding the _lines_ from the file to the list, not the numbers or people's names. Parsing those may be a bit more complicated, depending on what you want. Can you add an example of your desired output? – Evan Nov 06 '18 at 17:48
  • 35, Jerry. 20, bill. 20, Billy. 15, Dan – Adam Gulyas Jarvis Nov 07 '18 at 18:05

1 Answers1

0

Well, that was a bit of a longer walk than I expected.

with open("file.txt") as f:
    for line in f.readlines():
        new_text = line.strip().replace("[", "").replace("]", "").replace(" ", "").split("'")[:-1]
        new_text = [int(s) if s.isdigit() else s.title() for s in new_text]
        new_text = [(new_text[i],new_text[i+1]) for i in range(0,len(new_text),2)]
        new_text.sort(key=lambda tup: tup[0], reverse=True)

print(new_text)

Output:

[(35, 'Jerry'), (20, 'Bill'), (20, 'Billy'), (15, 'Dan')]

This returns a list (per line) of sorted, capitalized tuples. If your text formatting is critical, you'll have to do some more work from here. LMK if it is critical.

Help from:

Collect every pair of elements from a list into tuples in Python

How to sort (list/tuple) of lists/tuples?

Python - How to convert only numbers in a mixed list into float?

Evan
  • 2,121
  • 14
  • 27
  • it would be helpful if i didnt need to hard code it. the scores and names are in an external file and they need to come from that file.. – Adam Gulyas Jarvis Nov 08 '18 at 10:10
  • Edited to show how to read a file via context manager. You will have to make some changes w.r.t. to how the data is saved, ie printed to screen, saved to another file, etc. – Evan Nov 08 '18 at 16:57