英文:
How do I display the largest mean in python code?
问题
在Python代码中,如何显示最大的平均值?在这段代码中,计算了一组数字的平均值。我想要显示最大的平均值。
import csv
from statistics import mean
with open("numbers.csv") as f:
reader = csv.reader(f)
max_average = 0 # 初始化最大平均值
max_name = "" # 初始化对应的名称
for row in reader:
name = row[0]
these_grades = list()
for grade in row[1:]:
these_grades.append(int(grade))
average = mean(these_grades)
if average > max_average:
max_average = average
max_name = name
print("最大平均值是 %f,对应的名称是 %s" % (max_average, max_name))
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
英文:
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
答案1
得分: 0
以下是翻译好的代码部分:
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
英文:
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
答案2
得分: 0
如果你不需要额外的导入(因为没有引号括起的元素,所以简单的分割就足够了)。
如果你对一行代码的方式感兴趣:
maximum_mean = max(
(
sum(map(int, (grades := line.split(","))[1:])) / len(grades)
for line in open('numbers.csv')
)
)
print(maximum_mean) # 19.0
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论