简体   繁体   中英

Highest to Lowest from an average

I currently have a piece of code which finds an average from a file, so far I can find the average but cant sort this afterwards, below is my code which finds the average:

path = 'team1scores.csv'
with open(path) as f:
    entries = collections.Counter()
    total_scores = collections.Counter()
    for name,score in csv.reader(f):
        score = int(score)
        total_scores[name] += score
        entries[name] += 1

    for name in sorted(entries):
        ave_score = total_scores[name] / entries[name]
        print(name,ave_score)

In the same program I have used a highest to lowest sort at another point so would I somehow be able to add this...

path = 'team1cores.csv'
    with open(path) as f:
        entries = sorted(csv.reader(f), key=itemgetter(1), reverse=True)
    for name,score in entries:
        print(name,score)

...To the end of the average snippet. I have tried several different ways without any succession. Once the average part of the program is finished it returns these, this is what I need to sort.

Derek 4.0
Fred 9.0
George 7.0
Jake 3.6666666666666665

Hopefully it is a simple problem to fix.

You should think better the structure of your code: to sort the file reading process makes no sense... if you want to sort the average scores, you must register this information in a specific variable.

I believe you want to do something like this:

path = 'team1scores.csv'

entries = collections.Counter()
total_scores = collections.Counter()

with open(path) as f:
    for name,score in csv.reader(f):
        score = int(score)
        total_scores[name] += score
        entries[name] += 1

averages = collections.Counter()
for name in entries.keys():
    averages[name] = total_scores[name]/entries[name]

# `most_common(n)` will display the sorted `n` highest values
for name, score in averages.most_common():
    print(name, score)

# to sort the `n` from lowest, used most_common()[:`-n-1`:-1]
n = 2
for name, score in averages.most_common()[:-n-1:-1]:
    print(name, score)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM