v.m
v.m

Reputation: 1

Calculating average in python using nested lists

so the question is : average grade(grade list) return the average grade of all of the students in the list of lists grade list, where the inner lists contain a student ID and a grade.

this is what I have so far... but I don't know how to get the 2nd number for each list to get the average :/

grade_list=[['001',20],['002',45],['003',56]]
for i in grade_list:
   i= sum(i)/3
print (i)

Upvotes: 0

Views: 2492

Answers (4)

Jose Ricardo Bustos M.
Jose Ricardo Bustos M.

Reputation: 8164

you can try, list comprehension

grade_list=[['001',20],['002',45],['003',56]]
avg = sum([e[1] for e in grade_list])/len(grade_list)
print(avg)

40.333333333333336

or you can use for loop

grade_list=[['001',20],['002',45],['003',56]]
sumV = 0
for grade, value in grade_list:
    sumV += value

print(sumV / len(grade_list))

40.333333333333336

Or use map and itemgetter

from operator import itemgetter
grade_list=[['001',20],['002',45],['003',56]]
avg = sum(map(itemgetter(1),grade_list))/len(grade_list)
print(avg)

40.333333333333336

Or use mean if is python >= 3.4

from statistics import mean
from operator import itemgetter
grade_list=[['001',20],['002',45],['003',56]]
print(mean(map(itemgetter(1),grade_list)))

40.333333333333336

Or, you can use reduce

from functools import reduce
from operator import itemgetter
grade_list=[['001',20],['002',45],['003',56]]
print(reduce(lambda x, y: x + y/len(grade_list), map(itemgetter(1),grade_list), 0))

40.333333333333336

Or using pandas

import pandas as pd
grade_list=[['001',20],['002',45],['003',56]]
df = pd.DataFrame(grade_list)
print(df.mean(axis=0)[1])

40.3333333333

Upvotes: 4

LetzerWille
LetzerWille

Reputation: 5658

>>> grade_list=[['001',20],['002',45],['003',56]]

>>> print(round(sum([sublist[1] for sublist in grade_list ]) / len(grade_list),2))  

40.33

Upvotes: 0

Joseph Farah
Joseph Farah

Reputation: 2534

Use list indices. For example, replace the variable i in your code with i[1](not the for loop, just whatever you call inside of it). This will have your loop look at the SECOND element in your list, the grade. Right now it just looks at the whole list.

Also, your code is off. You want to go through all the second elements in the list as then divide by the total number of elements, so

average=0
for l in grade_list:
    average += l[1]
average/=len(grade_list)
print average

Remember, list indices start at 0.

Upvotes: 0

Paul Boddington
Paul Boddington

Reputation: 37645

Here is one way:

grade_list = [['001', 20], ['002', 45], ['003', 56]]
total = 0
for i in grade_list:
    total += i[1]
average = total / len(grade_list)
print(average)

Upvotes: 1

Related Questions