Sorting scores and names alphabetical, average, highest to lowest

后端 未结 1 1036
隐瞒了意图╮
隐瞒了意图╮ 2021-01-27 16:45

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 crea

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-27 17:14

    The first open, try:

    with open(filename, 'a+') as write_file:
    ....
    

    then the second open do:

    with open(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'
    
    
    def alphabetically(some_data):
        return OrderedDict(
            (k, some_data[k]['scores'])
            for k in sorted(some_data)
        )
    
    
    def by_score(some_data, descending=True):
        return OrderedDict(
            (k, sum(some_data[k]['scores']))
            for k in sorted(some_data,
                            key=lambda k: sum(some_data[k]['scores']),
                            reverse=descending)
        )
    
    
    def by_average(some_data, descending=True):
        def average(scores):
            return float(sum(scores)) / len(scores)
        return OrderedDict(
            (k, average(some_data[k]['scores']))
            for k in sorted(some_data,
                            key=lambda k: average(some_data[k]['scores']),
                            reverse=descending)
        )
    
    
    data = defaultdict(dict)
    with open(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)])
    

    0 讨论(0)
提交回复
热议问题