Don*_*len -3 python file list 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
Run Code Online (Sandbox Code Playgroud)
导入数据文件后的最终程序应如下所示......
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
Run Code Online (Sandbox Code Playgroud)
这是我的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()
Run Code Online (Sandbox Code Playgroud)
我不确定我在做什么......如何使用列表下标和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
Run Code Online (Sandbox Code Playgroud)