1

I currently have some data stored in a file that has a persons name and the score that they got when they played the game.

The data in the file looks like this:

Reece 0
John 5
Alex 2

I have tried using something like this:

with open("Scores.txt","r") as f:
    lines = sorted(f.readlines())
    print lines

But that just sorts them by the first letter in each of their names.

My output would need to be like this:

Reece 0
Alex 2
John 5

It is a relatively simple program and I am using Python 2.7

Any help would be amazing I can also provide any info on my program!

Reece
  • 59
  • 7

2 Answers2

2

A key would work like so:

with open("test.txt","r") as f:
     lines = sorted(iter(f), key=lambda x: int(x.partition(" ")[-1]))
     print lines

It will be memory efficient as you're creating only 1 list, and as you're iterating only once on the file's lines it will be quite fast.

Overall, I believe it's the fastest and most efficient method.

The full functionality including output would therefore be this:

with open("test.txt","r+") as f:
     lines = sorted(iter(f), key=lambda x: int(x.partition(" ")[-1]))
     f.seek(0)
     f.truncate()
     [f.write(l if l.endswith("\n") else l + "\n") for l in lines]
Bharel
  • 23,672
  • 5
  • 40
  • 80
  • Just to clarify, what this code does is go through each line in the file (**iter(f)**) and tell the _sorted()_ function to sort based off of the lambda (anonymous) function (**lambda x: int(x.partition(" ")[-1])**) which gets the score from each line by splitting it from the name in the line (**x.partition(" ")[-1]**). This will store the list of the lines in the file sorted by score into the variable _lines_ which is then printed at the end. – Mark May 10 '16 at 18:50
  • I don't believe you need **iter(f)** in the _sorted()_ function but rather you can just use **f** since the _sorted()_ function accepts an iterable as the first argument, which a file (f) is. – Mark May 10 '16 at 18:59
  • 1
    @Mark You're correct, I used `iter()` just for clarification, it causes no overhead at all, and it's really up to preference. – Bharel May 10 '16 at 19:39
0

Add cmp param to call of sorted:

with open("test.txt","r") as f:
     comparator = (lambda x,y: cmp(int(x.split(' ')[-1]), int(y.split(' ')[-1])))
     lines = sorted(f.readlines(), cmp=comparator)
     print lines
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82