Sorting Issue in Python
Question: I am attempting to sort a list which I have imported from a file in Python,
however I am having no luck, does anyone know what I am doing wrong?

    
    
    fr = open("database_results\Class_" + option + ".txt", 'r')
    lines = [line for line in fr if line.strip()]
    fr.close()
    lines.sort(key=int)
    fw = open("database_results\Class_" + option + ".txt", 'w')
    fw.writelines(lines)
    print(lines)
    print("ALERT: File successfully sorted numerically!")
    

The reason I am splitting the lines like this is because the data is stored
like this in the database:

    
    
    [Name: 'John Smith' Score: '7']
    [Name: 'Mitchel Jones' Score: '5']
    

I want the file to be sorted so the people who have received the highest score
are put to the top of the list. For the example above, this would be formatted
fine, because John has a higher score than Mitchel.


Answer: 1) You're using the key argument of sort wrong. Key specifies what part of
each item in your list is being used to sort. In my example, I'm supplying an
anonymous function which is saying that for each item in `l`, use the value at
index 0 for determining sort order

    
    
    l = [
        [3,1,2],
        [1,5,2],
        [0,9,3],
        [2,5,2]
    ]
    l.sort(key=lambda x : x[0])
    print l # prints [[0, 9, 3], [1, 5, 2], [2, 5, 2], [3,1,2]]
    

2) In order to do your sort, you'll likely need to perform a split on each
line, identify which index the score is sitting in, and cast it to an int.
This should do the sort:

`lines.sort(reverse=True, key=lambda x : int(x.strip().split('Score:
')[1].replace(']', '').replace('"', "").replace("'", "")))`

Here's what's happening:

  1. Split the string on score so we get back `["[Name: Blah Blah", "10]"]`
  2. We grab the item from the new list where the score is sitting (index 1)
  3. Replace the ], ', and " characters so we don't fail our int cast
  4. Cast the score to an int for numeric sorting

3) Probably not the best idea to write from the same file you were just
reading from. It would be better to put it somewhere like
`"database_results\Class_{0}_sorted.txt".format(option)"`

