我对此很陌生。我正在尝试进行最近6个小时的作业(:_(),这是我正在尝试的第七版代码,我有一个输入文件,其中包含名称和等级(10学生的名字以及每个学生的3个成绩,我尝试输入,但是直到弹出错误我看不到任何结果,我似乎在分配成绩并从中获取收益时很挣扎。还有其他方法吗?可以做到吗?
我试图将输入内容分成几个单独的学生,然后尝试使程序读取名称和年级,最后平均下来
with open('grades1.txt') as f:
content = [line.split() for line in f]
keys = content[0]
lst = list(zip([keys]*(len(content)-1), content[1:]))
x = [zip(i[0], i[1]) for i in lst]
z = [dict(i) for i in x]
Name,grade1,grade2,grade3 = x.split()
subjects = [float(name), float(grade1), float(grade2),
float(grade3)]
sum = 0
zero_count = 0
for subject in subjects:
sum += subject
if subject is 0:
zero_count +=
print(i, sum/(len(subjects)-zero_count)
我尝试的一切似乎都没有效果, 我不断收到语法错误等,这是作业的链接:
https://i.stack.imgur.com/cu0q1.png \
输入: 汤姆______ 5 4 4.5 戴恩________6 7 7 索林____8 8 3 梅里亚多克____ 1.0 2.3 4.5 山姆_________ 2.4 6.5 4.7 Gollem ________________ 1.8 6.7 5.3 佛罗多(Frodo)________ 9.1 3.7 8.5 甘达菲_____ 5.1 5.5 6.9 Peregrijn ________ 3.0 8.5 3.1 布鲁因____ 2.0 6.0 2.5
输出: 汤姆的平均成绩为 戴恩(Dain)的平均成绩为x Thorinha的平均成绩为x 梅里亚多克的平均成绩为x x 山姆的平均成绩为x Gollem的平均成绩为x Frod的平均成绩为x 甘道夫的平均成绩为x Peregrijn的平均成绩为x Bruine的平均成绩为x 报告结束
答案 0 :(得分:0)
不确定我是否了解您的代码,但这是一种相当简单的方法。查看注释以获取解释:
with open('grades1.txt') as f:
for line in f:
# Split on underscore to get name and grades (filtering out empty strings)
# Grades will be in one string, ex: "1.0 5.0 7.7"
name, grades_string = filter(None, line.split('_'))
# Split grades string on space and convert to each float
grades = [float(x) for x in grades_string.split(' ')]
# Calc average
average = sum(grades) / len(grades)
# Print results (TODO: formatting/rounding)
print name + ' has an average grade of ' + str(average)