How do I display the largest mean in python code?

Question:

How do I display the largest mean in python code?In this code, the average of a number of numbers is calculated. I want the largest average to be displayed

import csv
from statistics import mean

with open("numbers.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        name = row[0]
        these_grades = list()
        for grade in row[1:]:
            these_grades.append(int(grade))
        print("avrage of %s is %f" % (name, mean(these_grades)))

number.csv:

arad,19,19,20,18
sara,17,18,17,15
mahdi,12,13,15,16
saber,14,13,15,15
adel,19,14,17,16
Asked By: Hasan Hooman

||

Answers:

Use the following approach (accumulate average for each name):

import csv
from statistics import mean

with open('number.csv') as f:
    means = []
    reader = csv.reader(f)
    for row in reader:
        name, grades = row[0], map(int, row[1:])
        mean_ = mean(grades)
        means.append(mean_)
        print('average of %s: %f' % (name, mean_))
    print('Max average: {}'.format(max(means)))

average of arad: 19.000000
average of sara: 16.750000
average of mahdi: 14.000000
average of saber: 14.250000
average of adel: 16.500000
Max average: 19
Answered By: RomanPerekhrest

You could also do it without additional imports(you don’t have quoted elements so a simple split does the job)

If you interested in one-liner:

maximum_mean = max(
    (
        sum(map(int, (grades := line.split(",")[1:]))) / len(grades)
        for line in open('numbers.csv')
    )
)

print(maximum_mean)  # 19.0
Answered By: S.B
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.