-4

该程序应该读取 .txt 文件的各个行并找到每个人的测试分数的平均值。我在记事本中的 .txt 文件看起来像这样......

    John Smith 5 9 8 10 7
    Mary Brown 3 10 8 4 2
    Bob Black  7 10 9 10 8

而导入数据文件后的最终程序应该是这样的……

    Filename? file1.txt     ## file1.txt = the name of the data file the user input
    John Smith 7.8
    Mary Brown 5.4
    Bob Black 8.8

    Average over all students = 7.333333333333333

这是我的 Python 代码...

    def main():

        filename = input("Filename? ")
        filename = filename + ".txt"

        with open(filename,"r") as file:
            for lines in file:
            wholefile = lines.strip()
            print(wholefile)

        print("")

        average = 7.333333333333333      ## This is simply a placeholder!
        print("Average over all students =", average

    main()

我不确定我在做什么...如何使用列表下标和 if 语句完成此任务?

4

1 回答 1

6

一些指示:

>>> s = "John Smith 5 9 8 10 7"
>>> l = s.split()
>>> l
['John', 'Smith', '5', '9', '8', '10', '7']
>>> grades = [int(item) for item in l if item.isdigit()]
>>> grades
[5, 9, 8, 10, 7]
>>> grades = []     # or, if you haven't done list comprehensions yet:
>>> for item in l:
...     if item.isdigit():
...         grades.append(int(item))
...
>>> grades
[5, 9, 8, 10, 7]
>>> sum(grades)/len(grades)
7.8
于 2013-04-08T08:04:33.203 回答