Sort Average In A file
Question: I have a file with 3 scores for each person. Each person has their own row. I
want to use these scores, and get the average of all 3 of them. There scores
are separated by tabs and in descending order. For example:

    
    
    tam     10    6   11
    tom     3    7    3
    tim     5    4    6
    

these people would come out with an average of:

    
    
    tam    9
    tom    5
    tim    4
    

I want these to be able to print to the python shell, however not be saved to
the file.

    
    
    with open("file.txt") as file1:
        d = {}
        count = 0
        for line in file1:
            column = line.split()
            names = column[0]
            average = (int(column[1].strip()) + int(column[2].strip()) + int(column[3].strip()))/3
    
            count = 0
            while count < 3:
                d.setdefault(names, []).append(average)
                count = count + 1
        for names, v in sorted(d.items()):
            averages = (sum(v)/3)
            print(names,average)
        averageslist=[]
        averageslist.append(averages)

My code only finds the first persons average and outputs it for all of them. I
also want it to be descending in order of averages.


Answer: You can use the following code that parses your file into a list of (name,
average) tuples and prints every entry of the by average sorted list:

    
    
    import operator
    with open("file.txt") as f:
        data = []
        for line in f:
            parts = line.split()
            name = parts[0]
            vals = parts[1:]
            avg = sum(int(x) for x in vals)/len(vals)
            data.append((name, avg))
        for person in sorted(data, key=operator.itemgetter(1), reverse=True):
            print("{} {}".format(*person))
    

