【问题标题】:Calculating average grade wont succeed计算平均成绩不会成功
【发布时间】:2016-11-17 15:21:25
【问题描述】:

我必须计算某个人在 python 中的平均成绩。我收到了一个输入文件,结合它,我必须计算每个人的平均成绩。我试了很多,但我只得到了第一人的平均成绩。。有人能帮帮我吗?

输入文件如下:

Tom Bombadil__________6.5 5.5 4.5
Dain IJzervoet________6.7 7.2 7.7
Thorin Eikenschild____6.8 7.8 7.3
Meriadoc Brandebok____1.0 5.0 7.7
Sam Gewissies_________2.3 4.5 6.7

输出如下:

Tom Bombadilhas an average grade of 5.5
Dain IJzervoethas an average grade of 5.5
Thorin Eikenschildhas an average grade of 5.5
Meriadoc Brandebokhas an average grade of 5.5
Sam Gewissieshas an average grade of 5.5

我使用了这个代码:

def names(lines):
    for i in lines:
        invoer_split = i.split("_")
        first_name = invoer_split[0]
        print first_name + "has an average grade of %.1f" %(average_grade(names))

def average_grade(names):
    for i in lines:
        grades_split = i.split("_")
        grades = grades_split[-1]
        grades_float = map(float,grades.split())
        grades_average = sum(grades_float)/3
        return grades_average

grades_file = open('grades1+2.in')
lines = grades_file.readlines()

names(lines)
average_grade(names)

【问题讨论】:

  • 请不要破坏您的帖子。

标签: python list output


【解决方案1】:

不要分别处理姓名和成绩,而是同时进行。我们将输入更改为字典,将字符串映射为浮点数。

with open('filename') as f:
    grades_dict = {}
    for line in f:
        name, *underscores, grades = line.split('_') #I forget when this syntax became a thing.  You might have to assign these separately
        grades = list(map(float, grades.split()))
        grades_dict[name] = sum(grades)/len(grades)

for name, grade in grades_dict.items():
    print('{0} has an avergae grade of {1}'.format(name, grade))

【讨论】:

  • 哇,这对我来说看起来很复杂.. 对我自己的代码稍作改动难道不可能吗?
  • 您遇到的问题主要是因为您分别获取名称和值,因此稍后您无法将等级与它们的名称匹配。以上哪部分你有问题,我可以给你解释一下。
【解决方案2】:

作为 Patrick 的解决方案的替代方案,您可以使用它。

def average_grade(grades_string):
    # split on whitespace
    grades = grades_string.split(' ')
    # convert to floats (we convert map to list for python3 compatibility)
    grades = list(map(float, grades))
    # return the average
    return sum(grades)/len(grades)

# This is the same as "lines = open()", but closes the file after we finish
with open('grades1+2.txt') as lines:
    # Start iterating
    for line in lines:
        # When we split by underscores, we will get three parts:
        # the name; the empty string (where underscores were); the grades.
        # We can do that in one assignment
        name, ignore_this, grades_str = line.split('_')
        # now print the result (converting average to string)
        print(name + ' has an average of ' + str(average_score(grades_str)))

【讨论】:

    猜你喜欢
    • 2019-08-25
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    相关资源
    最近更新 更多