Skip to content Skip to sidebar Skip to footer

Sorting Scores And Names Alphabetical, Average, Highest To Lowest

Back again with another question about my project. So I've tried to sort my scores in descending order in my text file. However, it outputs a syntax error. The filename is created

Solution 1:

The first open, try:

withopen(filename, 'a+') as write_file:
....

then the second open do:

withopen(filename, 'r+') as read_file:
...

Maybe it will work

EDIT

Now regarding first your file parsing and the sorting methods, I came up with this:

from collections import defaultdict
from collections import OrderedDict

filename = 'file.txt'defalphabetically(some_data):
    return OrderedDict(
        (k, some_data[k]['scores'])
        for k insorted(some_data)
    )


defby_score(some_data, descending=True):
    return OrderedDict(
        (k, sum(some_data[k]['scores']))
        for k insorted(some_data,
                        key=lambda k: sum(some_data[k]['scores']),
                        reverse=descending)
    )


defby_average(some_data, descending=True):
    defaverage(scores):
        returnfloat(sum(scores)) / len(scores)
    return OrderedDict(
        (k, average(some_data[k]['scores']))
        for k insorted(some_data,
                        key=lambda k: average(some_data[k]['scores']),
                        reverse=descending)
    )


data = defaultdict(dict)
withopen(filename, 'r+') as f:
    for line in f.read().splitlines():
        name, score = line.split(' : ')
        scores = data[name].get('scores', [])
        scores.append(int(score))
        data[name]['scores'] = scores

print alphabetically(data)
print by_score(data)
print by_average(data)

Output:

OrderedDict([('ADAM', [2]), ('Da', [3, 0, 1]), ('Dadsid', [4]), ('Davd', [3, 4]), ('Dliid', [9]), ('Dloed', [1]), ('Dsid', [3]), ('lukedd', [8]), ('mathe', [4, 12])])
OrderedDict([('mathe', 16), ('Dliid', 9), ('lukedd', 8), ('Davd', 7), ('Da', 4), ('Dadsid', 4), ('Dsid', 3), ('ADAM', 2), ('Dloed', 1)])
OrderedDict([('Dliid', 9.0), ('lukedd', 8.0), ('mathe', 8.0), ('Dadsid', 4.0), ('Davd', 3.5), ('Dsid', 3.0), ('ADAM', 2.0), ('Da', 1.3333333333333333), ('Dloed', 1.0)])

Post a Comment for "Sorting Scores And Names Alphabetical, Average, Highest To Lowest"