Tom
Tom

Reputation: 21

How to sort a list of scores in Python?

I have a list of scores like this:

 Username Tom, Score 7
 Username Tom, Score 13
 Username Tom, Score 1
 Username Tom, Score 24
 Username Tom, Score 5

I would like to sort the list so it is in top 5 order, then truncate the list to remove the ones not in the top 5, then print this top 5,

My code so far is:

   scores = [(username, score)]
        for username, score in scores:
            with open('Scores.txt', 'a') as f:
                for username, score in scores:
                    f.write('Username: {0}, Score: {1}\n'.format(username, score))
                    scoreinfo = f.split()
                    scoreinfo.sort(reverse=True)

This is what I have so far, and this is the error I get:

Traceback (most recent call last):
   File "Scores.txt", line 92, in <module>
     songgame()
   File "Scores.txt", line 84, in songgame
     scoreinfo = f.split()
 AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Any ideas how to solve this, what it means and what I can do next?

Upvotes: 2

Views: 1087

Answers (2)

Sam The Sid
Sam The Sid

Reputation: 93

I'm not quite sure on what object is your list exactly. Is it from another file ? Is it a python object ? I've considered it was a python list like

scores = [("Tom", 7), ("Tom", 13), ("Tom", 1), ("Tom", 24), ("Tom", 5)]

I change few things to your code. I begin to sort this list with the second object with the scores.sort()function. On it is sorted, you just have to write it in your file.

def your_function(top_list=5):
    scores = [("Tom", 7), ("Tom", 13), ("Tom", 1), ("Tom", 24), ("Tom", 5)]
    scores.sort(key=lambda score: score[1], reverse=True)

    with open('Scores.txt', 'w') as f:
        for i in range(top_list):
            username, score = scores[i]
            f.write('Username: {0}, Score: {1}\n'.format(username, score))

Upvotes: -1

ruohola
ruohola

Reputation: 24018

This should do the job quite nicely, feel free to ask if there's something you don't understand;

scores = [('Tom', 7), ('Tom', 13), ('Tom', 1), ('Tom', 24), ('Tom', 5)]

scores.sort(key=lambda n: n[1], reverse=True)
scores = scores[:5]  # remove everything but the first 5 elements

with open('Scores.txt', 'w+') as f:
    for username, score in scores:
        f.write('Username: {0}, Score: {1}\n'.format(username, score))

After running the program the Scores.txt looks like this:

Username: Tom, Score: 24
Username: Tom, Score: 13
Username: Tom, Score: 7
Username: Tom, Score: 5
Username: Tom, Score: 1

Upvotes: 2

Related Questions