Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用列表下标查找数据文件中的平均行数_Python_List_File_Text Files - Fatal编程技术网

Python 使用列表下标查找数据文件中的平均行数

Python 使用列表下标查找数据文件中的平均行数,python,list,file,text-files,Python,List,File,Text Files,程序应该读取.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

程序应该读取.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
导入数据文件后的最终程序应该如下所示

    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语句完成此任务?

一些指针:

>>> 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

好的,看来这是你的家庭作业。那么你对剩下的代码有什么想法吗?你为什么把这个打印文件放在那里?