Sorting a text file with strings and digits on each line - Python 3
Question: I have a text file I made with some runners and their race times in which
looks like this:

    
    
    Dylan , 3.6
    Tom , 4.2
    Jack , 1.4
    Dave , 8.8
    Mick , 5.2
    John , 11.3
    Matt , 7.6
    Ben , 9.7
    Joe , 3.9
    Chris , 3.3
    

I have a new line for each new race participant and their race time after a
comma.

How can I sort this text file so the person with the fastest time is at the
top. The code I used to generate the test file looks like this:

    
    
    def runnerData():
        thefile = open("race.txt" , "w")
        names = ["Dylan" , "Tom" , "Jack" , "Dave" , "Mick" , "John" , "Matt" , "Ben" , "Joe" , "Chris"]
        times = ["3.6" , "4.2" , "1.4" , "8.8" , "5.2" , "11.3" , "7.6" , "9.7" , "3.9" , "3.3"]
        zipped = zip(names, times)
        for aname,atime in zipped:
            thefile.write("%s , %s\n" %(aname,atime))
    
    runnerData()
    

I have only just started using Python and am not familiar with a lot of it -
still learning! :)

Thanks.

EDIT:

The code I used to generate the file ok and i'm happy it works - The task I
have been set is to write a new file using the text file I have generated to
display the winner of the race.


Answer: You need to sort your `zipped` list based on second element,you can use
[_`sorted()`_](https://docs.python.org/2/library/functions.html#sorted)
function with a proper `key` :

    
    
    from operator import itemgetter
    def runnerData():
        thefile = open("race.txt" , "w")
        names = ["Dylan" , "Tom" , "Jack" , "Dave" , "Mick" , "John" , "Matt" , "Ben" , "Joe" , "Chris"]
        times = ["3.6" , "4.2" , "1.4" , "8.8" , "5.2" , "11.3" , "7.6" , "9.7" , "3.9" , "3.3"]
        zipped = zip(names, times)
        for aname,atime in sorted(zipped,key=float(itemgetter(1)),reverse=True):
                thefile.write("%s , %s\n" %(aname,atime))
    
    runnerData()
    

And if you read the preceding file you can do :

    
    
    l=[]
    for line in open('your_file'):
       l.append(line.split(','))
    

So the `l` would be :

    
    
    [['Dylan ', ' 3.6'], ['Tom ', ' 4.2'], ['Jack ', ' 1.4'], ['Dave ', ' 8.8'], ['Mick ', ' 5.2'], ['John ', ' 11.3'], ['Matt ', ' 7.6'], ['Ben ', ' 9.7'], ['Joe ', ' 3.9'], ['Chris ', ' 3.3']]
    

then you can use the preceding `sorted()` function to sort your list :

    
    
    sorted(l,key=float(itemgetter(1)),reverse=True)
    

