Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the average of a row in a 2D list in python?

I'm new to Python and I'm working with a 2D list and not exactly sure how to get the average of the rows.

For example I have this list:

myList = [[70, 80, 90], [30, 40, 50]]

and I would like to get the average of the first and second row.

Something like this:

(70 + 80 + 90)/3 = 80

(30 + 40 + 50)/3 = 40

I'm implementing my print_student_average function, but I'm a little lost. Someone tell me what I'm doing wrong please.

Here's my code:

def main():
    myList = [[70, 80, 90], [30, 40, 50]]

    print(print_student_average(myList))
    print_exam_average(myList)

def print_student_average(myList):

    total_sum = [sum(i) for i in range(len(myList))]
    average = total_sum/3

    return average

def print_exam_average(myList):

    col_totals = [ sum(x)/2 for x in zip(*myList) ]

    for col in col_totals:
        print("the average of the exam is: ", col)


main()
like image 282
Devmix Avatar asked Dec 25 '22 07:12

Devmix


1 Answers

If you want, you can use numpy package and its function mean.

To compute the average mark of each student, given myList, the code would look like:

import numpy

def print_student_average(myList):
    students_avg = numpy.mean(myList, axis=1)
    for avg in students_avg:
        print(avg)
    return students_avg

Note that axis=1 determines that the average is calculate over the rows. With the list in the example provided, the output is:

80.0
40.0

Similarly, you can get the average for every exam using the same numpy function:

def print_exams_average(myList):
    exams_avg = numpy.mean(myList, axis=0)
    for avg in exams_avg:
        print(avg)
    return exams_avg

In this case axis=0 to get the average over columns, and the result for the list provided in the example is:

50.0
60.0
70.0

About the problem in your print_student_average,

 total_sum = [sum(i) for i in range(len(myList))]

is the main problem. range returns a list of integers starting from 0 to the length of the list, which in the example is 2. With the for statement you iterate over each value of the list from range, and then you are trying to use sum over an integer, which does not work as it is not a list. The solution that follows more closely your code is already provided in another answer.

like image 180
albertoql Avatar answered Jan 06 '23 03:01

albertoql