Python Forum
How Do I Calculate an Average and Sort File Data in Python?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How Do I Calculate an Average and Sort File Data in Python?
#1
Hi everyone, I’m Jason and this is a homework problem my teacher gave me. I’m struggling with it, can someone help? Geometry Dash
Write a Python program that:
1. Reads a text file named grades.txt containing student names and their numeric scores (0–100), one per line, like:
Alice 92
Bob 78
Charlie 85
David 78
Emma 92
2. Calculates the average score.
3. Prints all student names whose score is above the average.
4. Sorts the output by score descending, and if scores are tied, by name ascending.
I tried reading the file and computing the average, but I’m not sure how to sort and filter properly.
def read_scores(filename):
    with open(filename) as f:
        lines = f.readlines()
    scores = []
    for line in lines:
        name, score = line.split()
        scores.append((name, int(score)))
    return scores

data = read_scores('grades.txt')
# … I’m stuck here …
print(data)
Can someone show how to finish this and output the correct result?
Thanks!
Link Removed
Gribouillis write Jan-20-2026, 06:33 AM:
Clickbait link removed. Please read What to NOT include in a post
Reply
#2
If you had the names and other data of thousands of students, you would probably use a csv file to save it, or a database. Given this data:

Quote:Name,score
Alice Springs,92
Bob Marley,78
Charlie Chaplin,85
David Goliath,78
Emma Thompson,92
Donald Trump,5
Keir Starmer,4
Bejamin Netanyahu,0
Castro Fidel,78

saved as csv, you can get the data like this:

import csv

student_scores = '/home/peterr/temp/student_scores.csv'

with open(student_scores) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    data = []
    for row in csv_reader:
        data.append(row)
You don't want the column headers, so try a slice of data

# data is a list of lists
# first row is column headers so get rid of it
# all data are strings to start with
wanted = data[1:]
Data is now a list of lists:

for w in wanted:
    print(w)
You will see:

Output:
['Alice Springs', '92'] ['Bob Marley', '78'] ['Charlie Chaplin', '85'] ['David Goliath', '78'] ['Emma Thompson', '92'] ['Donald Trump', '5'] ['Keir Starmer', '4'] ['Bejamin Netanyahu', '0'] ['Castro Fidel', '78']
You know, to get the average score you need to add up all the scores, then divide by the number of scores.

scores = [int(w[1]) for w in wanted]
total = sum(scores)
average_score = sum(scores) / len(scores)
You can print(average_score) I get 56.888888888888886

Now for sorting lists, there are 2 easy ways, look here in the docs.

You can use alist.sort() which sorts your list and changes it, or, (I think it is better to keep the old data first), use sorted(a_list).

Practice using sorted() a bit, till you get the hang of it. The docs are very helpful.

result = sorted(a_list)
This returns a new list

result1 = sorted(scores)
result1 looks like:

Output:
[0, 4, 5, 78, 78, 78, 85, 92, 92]
sort() and sorted() can use a parameter: reverse=True to sort descending

result2 = sorted(scores, reverse=True)
result2 looks like:

Output:
[92, 92, 85, 78, 78, 78, 5, 4, 0]
To sort using the names as a secondary key after the scores, read the docs in the link I posted. There is an example very similar to what you want to do.

Remember: whatever you want to do in Python, 99.99% of the time, it has already been done, just search the web.

I personally like realpython.com for info on how to do things, but there are so many other good websites out there for info on Python! Just search!

Later on when your csv file is more complex, you can open it using the module pandas, which can do all kinds of magic!

Have fun!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple Method to calculate average and grade ajitnayak1987 8 11,487 Apr-28-2022, 06:26 AM
Last Post: rayansaqer
  Calculate time taken to cool down a pool in python edwinostby 0 2,691 May-24-2021, 04:12 PM
Last Post: edwinostby
  how to sort a list without .sort() function letmecode 3 5,407 Dec-28-2020, 11:21 PM
Last Post: perfringo
  How to calculate the lexical diversity average (with 1000 window word length) AOCL1234 6 5,894 Jul-27-2020, 06:16 AM
Last Post: DPaul
  Read data from a CSV file in S3 bucket and store it in a dictionary in python Rupini 3 10,938 May-15-2020, 04:57 PM
Last Post: snippsat
  Data extraction from (multiple) MS Word file(s) in python Den0st 8 21,328 Sep-19-2019, 10:07 PM
Last Post: Den0st
  Calculate using Python HoustonM11 2 3,197 Aug-26-2019, 03:43 AM
Last Post: millpond
  [split] Manual Sort without Sort function fulir16 2 4,633 Jun-02-2019, 06:13 AM
Last Post: perfringo
  Manual Sort without Sort function dtweaponx 26 60,885 Jun-01-2019, 06:02 PM
Last Post: SheeppOSU
  Sort Matrices by Mean Value Obtained (OpenCV, Python and Numpy) danny_paez 1 3,164 May-03-2019, 12:21 PM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020