Ranger
Ranger

Reputation: 43

Strings and Integers in Python

This is my data file (called “studentdata.txt”)

joe 10 15 20 30 40
bill 23 16 19 22
sue 8 22 17 14 32 17 24 21 2 9 11 17
grace 12 28 21 45 26 10
john 14 32 25 16 89

I need to calculate the average grade for each student and print out the student’s name along with their average grade. I can extract the name with no problem and determine the number of exam scores, but I can not figure out how to sum the exam scores. This is what I have so far:

file=open("studentdata.txt","r")

for aline in file:    
    data=aline.split()    

    print((data[0]),"Average grade:")
    print(len(data[1:]))


file.close()  

Upvotes: 1

Views: 491

Answers (3)

U13-Forward
U13-Forward

Reputation: 71560

Try the below code, just split each line on spaces then get the numbers not with the name so the indexing will be the i.strip().split()[1:] then use map to convert that into an integer then use statistics.mean to get the average:

from statistics import mean
d = {}
with open('studentdata.txt','r') as f:
   for i in f.readlines():
      d[i.split()[0]] = mean(list(map(int,i.strip().split()[1:])))
print(d)

Output:

{'joe': 23.0, 'bill': 20.0, 'sue': 16.166666666666668, 'grace': 23.666666666666668, 'john': 35.2}

Upvotes: 0

Mridula Gunturi
Mridula Gunturi

Reputation: 187

Try this?

file = open("studentdata.txt", "r")
for aline in file:
    data = aline.split()

    # Convert list of string numerals to int
    grades = [int(grade) for grade in data[1:]]

    # Find average by dividing sum by length of numbers list
    average = sum(grades)/len(data[1:])

    print((data[0]), "Average grade:", str(average))

file.close()

Upvotes: 1

user3483203
user3483203

Reputation: 51165

It seems like you have most of this already done, and you already have a good grasp of how to partition each line into the two components you need, so you're real close!

First, since the data is being read in as a string, you need to convert part of your data to integers:

for line in file:
    tmp = line.split()
    name, scores = tmp[0], list(map(int, tmp[1:]))

This will give us each name, along with a list of scores as integers. Now all you have to do is find the average:

average = sum(scores)/len(scores)

Let's tie it all together by assigning to a dictionary:

dct[name] = average

And we get:

{'joe': 23.0, 'bill': 20.0, 'sue': 16.166666666666668, 'grace': 23.666666666666668, 'john': 35.2}

Upvotes: 3

Related Questions